Why do sort function behaves like this? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why do sort function behaves like this?

https://code.sololearn.com/cuVFR40hxs6V/?ref=app In the code mentioned above when a=a.sort() is written the code outputs the list to be none, why is the output such and when normal a.sort() is written the output is sorted list, I'm very much confused about it. If anyone could explain this it would be of great help.

19th Jun 2018, 4:14 AM
Anshul Aggarwal
Anshul Aggarwal - avatar
3 Answers
+ 6
The a.sort() method sorts the list but doesn't return anything. If you want to return a sorted version of the list, use the sorted(a) function. https://wiki.python.org/moin/HowTo/Sorting/ https://www.codecademy.com/en/forum_questions/548e5b1b9376762f5b007e5a
19th Jun 2018, 4:24 AM
David Ashton
David Ashton - avatar
+ 1
Because the sort() list method does NOT return the sorted array. https://www.tutorialspoint.com/JUMP_LINK__&&__python__&&__JUMP_LINK/list_sort.htm As to WHY it doesn't, see the answer here: https://stackoverflow.com/questions/7301110/why-does-return-list-sort-return-none-not-the-list Look especially at the 3rd answer, pointing here to an email from Guido van Rossum, python's author: https://mail.python.org/pipermail/python-dev/2003-October/038855.html Methods returning None are hinting you that they modify the original object and not creating a new one.
19th Jun 2018, 4:30 AM
Udi Finkelstein
Udi Finkelstein - avatar
0
Python sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations). http://net-informations.com/python/ds/listsort.htm
26th Mar 2020, 7:01 AM
rahul kumar
rahul kumar - avatar