Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sorting list
#1
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())
Reply
#2
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]
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List Sorting Problem ZZTurn 5 3,513 Sep-22-2022, 11:23 PM
Last Post: ZZTurn
  Sorting List finndude 9 5,027 Jan-27-2022, 09:37 PM
Last Post: Pedroski55
  sorting a list of lists by an element leapcfm 3 3,419 Sep-10-2021, 03:33 PM
Last Post: leapcfm
  Sorting list of names using a lambda (PyBite #5) Drone4four 2 4,155 Oct-16-2020, 07:30 PM
Last Post: ndc85430
  list sorting question DPaul 5 4,673 Jun-17-2020, 02:23 PM
Last Post: ndc85430
  sorting list of lists pframe 5 36,754 Apr-17-2020, 09:31 PM
Last Post: Larz60+
  Converting parts of a list to int for sorting menator01 2 3,501 Nov-03-2019, 03:00 PM
Last Post: menator01
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 7,265 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER
  sorting a list of tuples based on date bluefrog 2 7,666 Aug-10-2018, 02:31 AM
Last Post: ichabod801
  Sorting list of lists with string and int Otbredbaron 6 6,511 May-07-2018, 06:04 AM
Last Post: buran

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.