I am starting to learn Python.
Can someone explain why sort() returns None?
alist.sort() ## correct
alist = blist.sort() ## NO incorrec
alist.sort()
sorts alist
in-place, modifying alist
itself.
If you want a new list to assign somewhere, use blist = sorted(alist)
list.sort()
: http://docs.python.org/library/stdtypes.html#mutable-sequence-typessorted()
: http://docs.python.org/library/functions.html#sortedUse the following:
alist = sorted(blist)
When you want to perform the sorting on same list then you have to use sort()
method of list. But If you dont want to change the sequence of original list but you need a sorted copy of the original list then use sorted()
inbuilt function.
Answering to his question, it returns none because the method always returns None. When you use it, it automatically modifies the list, so it does not keep the original intact (ie it does not return a sorted copy of the list).