Python列表sort()函数调用返回None值的问题求助
list.sort() return None in Python? Hey there! Let's break down why you're seeing None when running that code.
The key thing to know about Python's list.sort() method is that it's an in-place sorting function. That means it modifies the original list directly to put its elements in order, but it doesn't return a new sorted list. When you assign x = cars.sort(), you're assigning the method's return value to x—and since sort() doesn't produce a new list to return, it gives you None instead.
Fixes to get the sorted result you want:
1. Sort in-place, then print the original list
If you don't need to keep the original unsorted list, just call sort() first, then print the modified cars list:
cars = ['Ford', 'BMW', 'Volvo'] cars.sort() # This changes the original 'cars' list print(cars) # Now prints the sorted list: ['BMW', 'Ford', 'Volvo']
2. Use sorted() to get a new sorted list
If you want to keep the original list intact and store the sorted version in a new variable, use the built-in sorted() function instead. It returns a brand-new sorted list without touching the original:
cars = ['Ford', 'BMW', 'Volvo'] x = sorted(cars) # sorted() returns a new sorted list print(x) # Prints ['BMW', 'Ford', 'Volvo'] print(cars) # Original list remains unchanged: ['Ford', 'BMW', 'Volvo']
To sum it up: list.sort() mutates the original list and returns None, while sorted() creates and returns a new sorted list. Pick whichever fits your use case!
内容的提问来源于stack exchange,提问作者Sujeet maurya

