+ 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.
3 ответов
+ 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
+ 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.
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