Reputation: 427
Can anyone please tell whats wrong with this code? I need to output the sorted list and the reverse list
def sort_num():
count=1;
global a
a=[]
while count<11:
no=int(raw_input("no %d:" %count))
a.append(no)
count+=1
print a
print a.reverse()
print a.sort()
and my output is:
[2, 33, 4, 11, 7, 8, 5, 6, 33, 0]
None
None
Upvotes: 2
Views: 10388
Reputation: 16940
Bit explanation about why list.sort() doesn't return the sorted list?
In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort(), sorts the list in place.
In order to remind you of that fact, it does not return the sorted list. This way, you won’t be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around. In that case use builtin sorted() function.
sorted() is a built-in function:
>>> help(sorted)
Help on built-in function sorted in module __builtin__:
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
>>>
list.sort() is a method of list which will change on the list itself:
>>> help(list.sort)
Help on method_descriptor:
sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
Snippet:
>>> ls = [3,2,1]
>>> sorted(ls)
[1, 2, 3]
>>> ls
[3, 2, 1]
>>> ls.sort()
>>> ls
[1, 2, 3]
>>>
Hope that will clear your doubt.
Upvotes: 2
Reputation: 637
This will give you a sorted version of the array.
sorted(a, reverse=True)
If you want to sort in-place:
a.sort(reverse=True)
Upvotes: 1
Reputation: 1374
Another option is to call the builtin reversed
(returns an iterator) and sorted
(returns a sorted copy) methods.
print list(reversed(a))
print sorted(a)
Upvotes: 1
Reputation: 239453
list.reverse
and list.sort
are inplace reversing and sorting functions. They return None
. So, you have to print a
separately, like this
a.reverse()
print a
a.sort()
print a
Upvotes: 5