list sort() function bring backs None - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: list sort() function bring backs None (/thread-36704.html) |
list sort() function bring backs None - CompleteNewb - Mar-20-2022 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 Nonewhy doesn't it just return [1,1,1,1,1] and what kind i do to bypass that problem? RE: list sort() function bring backs None - menator01 - Mar-20-2022 list1 = [1,1,1,1,1] list2 = list1 list2.sort() print(list2)
RE: list sort() function bring backs None - Yoriz - Mar-20-2022 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) Use sorted if you want to get a sperate sorted versionlist1 = [3, 4, 1, 2] list2 = sorted(list1) print(list1) print(list2)
@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)
RE: list sort() function bring backs None - CompleteNewb - Mar-20-2022 thank you RE: list sort() function bring backs None - deanhystad - Mar-21-2022 @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/stdtypes.html?highlight=list%20sort#list.sort That references a nice article all about sorting. https://docs.python.org/3/howto/sorting.html#sortinghowto 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. RE: list sort() function bring backs None - CompleteNewb - Mar-25-2022 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 RE: list sort() function bring backs None - Larz60+ - Mar-26-2022 Don't apologize, at one point or another we've all been there, and that is what this forum is all about! |