Posts: 75
Threads: 20
Joined: Dec 2020
i have a program that gives back a random list of numbers which i then sort using .sort() , but then this happened:
1 2 3 |
list1 = [ 1 , 1 , 1 , 1 , 1 ]
list2 = list1.sort[]
print (list2)
|
output
why doesn't it just return
[1,1,1,1,1]
and what kind i do to bypass that problem?
Posts: 1,145
Threads: 114
Joined: Sep 2019
1 2 3 4 |
list1 = [ 1 , 1 , 1 , 1 , 1 ]
list2 = list1
list2.sort()
print (list2)
|
Output: [1, 1, 1, 1, 1]
Posts: 2,168
Threads: 35
Joined: Sep 2016
Mar-20-2022, 09:04 PM
(This post was last modified: Mar-20-2022, 09:13 PM by Yoriz.)
That is because the list sort method sorts in place and returns None
1 2 3 4 |
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
1 2 3 4 |
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
1 2 3 4 5 |
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
Posts: 75
Threads: 20
Joined: Dec 2020
Posts: 6,827
Threads: 20
Joined: Feb 2020
Mar-21-2022, 04:55 PM
(This post was last modified: Mar-21-2022, 06:55 PM by deanhystad.)
@newb
You really need to do more research into these simple questions. It is easy to google "Why does sort return None?", but I prefer reading the Python documentation because I always learn more. This talks about all the things you can do with lists, including sorting.
https://docs.python.org/3/library/stdtyp...#list.sort
That references a nice article all about sorting.
https://docs.python.org/3/howto/sorting....rtinghowto
You post a question here and you get your answer. Eventually. When you search the documentation you get the answer faster, and learn more that is related to your question.
Posts: 75
Threads: 20
Joined: Dec 2020
Mar-25-2022, 11:57 PM
(This post was last modified: Mar-26-2022, 12:00 AM by Yoriz.
Edit Reason: removed unnecessary quote of previous post
)
Thank you, I'll check out the ressources you just gave me before asking question here in the future but trust me i search the web before asking question, i just don't seem to be good at it
Posts: 12,050
Threads: 487
Joined: Sep 2016
Mar-26-2022, 03:34 AM
(This post was last modified: Mar-26-2022, 08:58 AM by Yoriz.
Edit Reason: Removed unnecessary quote of previous post
)
Don't apologize, at one point or another we've all been there, and that is what this forum is all about!
|