1
opt=[]
opt=["opt3","opt2","opt7","opt6","opt1"]
for i in range(len(opt)):
     print opt[i]

Output for the above is

opt3,opt2,opt7,opt6,opt1

How to sort the above array in ascending order..

2
  • 1
    for i in range(len(opt)) is unPythonic. Use for elt in opt instead. Commented Aug 12, 2010 at 17:43
  • You do not need the first line (opt=[]). Commented Aug 12, 2010 at 19:15

3 Answers 3

8

Use .sort() if you want to sort the original list. (opt.sort())

Use sorted() if you want a sorted copy of it.

Sign up to request clarification or add additional context in comments.

Comments

2

print sorted(opt)

Comments

0

Depends on whether or not you want a natural sort (which I think you do) or not.

If you use sorted() or .sort() you'll get:

>>> opt = ["opt3", "opt2", "opt7", "opt6", "opt1", "opt10", "opt11"]
>>> print sorted(opt)
['opt1', 'opt10', 'opt11', 'opt2', 'opt3', 'opt6', 'opt7']

While you'll probably want ['opt1', 'opt2', 'opt3', 'opt6', 'opt7', 'opt10', 'opt11'].

If so you'll want to look into natural sorting (there are various variations on the function mentioned in that article).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.