Python Forum
sorting list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: sorting list (/thread-24154.html)



sorting list - arian29 - Feb-02-2020

Why does print(listA.sort()) return None ? But if I sort first and then print(listA), returns the sorted list items.

listA=[1,2,3,9,8,7,6]
print(listA[1])
print(listA.sort())



RE: sorting list - ibreeden - Feb-02-2020

Yes you are right. One might expect a sorted list is returned, but look at the definition of list.sort. It says:
Quote:This method sorts the list in place
. Apparently this means the list is sorted by this method. But it returns nothing.
>>> listA=[1,2,3,9,8,7,6]
>>> print(listA.sort())
None
>>> print(listA)
[1, 2, 3, 6, 7, 8, 9]



RE: sorting list - ndc85430 - Feb-02-2020

That's what "in place" means - the original list is mutated, so there's nothing to return. sorted on the other hand will return a new, sorted list.