Python Forum
list sort() function bring backs None
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list sort() function bring backs None
#3
That is because the list sort method sorts in place and returns None
list1 = [3, 4, 1, 2]
list2 = list1.sort()
print(list1)
print(list2)
Output:
[1, 2, 3, 4] None
Use sorted if you want to get a sperate sorted version
list1 = [3, 4, 1, 2]
list2 = sorted(list1)
print(list1)
print(list2)
Output:
[3, 4, 1, 2] [1, 2, 3, 4]


@menator01 Your code has two variables list1 & list2 that point to the same list object
list1 = [3, 4, 1, 2]
list2 = list1
list2.sort()
print(list1)
print(list2)
Output:
[1, 2, 3, 4] [1, 2, 3, 4]
BashBedlam and Larz60+ like this post
Reply


Messages In This Thread
RE: list sort() function bring backs None - by Yoriz - Mar-20-2022, 09:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 2 739 Apr-29-2024, 04:38 PM
Last Post: Calab
  list.sort() returning None SmallCoder14 8 815 Mar-19-2024, 09:49 PM
Last Post: SmallCoder14
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,397 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  [solved] Sort list paul18fr 5 2,986 Aug-18-2021, 06:34 AM
Last Post: naughtyCat
  Sort Function: <' not supported between instances of 'float' and 'tuple' quest 2 8,242 Apr-30-2021, 07:37 PM
Last Post: quest
  Sort List of Lists by Column Nju 1 13,607 Apr-13-2021, 11:59 PM
Last Post: bowlofred
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,634 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  How to sort os.walk list? Denial 6 11,937 Oct-10-2020, 05:28 AM
Last Post: Denial
  Cannot bring up anaconda in Docker image ErnestTBass 1 1,895 Aug-15-2020, 04:12 AM
Last Post: ndc85430
  I created a function that generate a list but the list is empty in a new .py file mrhopeedu 2 2,396 Oct-12-2019, 08:02 PM
Last Post: mrhopeedu

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020