Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sort method is not working inside the user defined function

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 
like image 256
macavity Avatar asked Feb 09 '26 18:02

macavity


2 Answers

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
like image 104
thefourtheye Avatar answered Feb 12 '26 06:02

thefourtheye


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.

like image 32
James Avatar answered Feb 12 '26 06:02

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!