i have a program that gives back a random list of numbers which i then sort using .sort() , but then this happened:
list1 = [1,1,1,1,1]
list2 = list1.sort[]
print(list2)
output
None
why doesn't it just return
[1,1,1,1,1]
and what kind i do to bypass that problem?
list1 = [1,1,1,1,1]
list2 = list1
list2.sort()
print(list2)
Output:
[1, 1, 1, 1, 1]
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]
@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.
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
Don't apologize, at one point or another we've all been there, and that is what this forum is all about!