You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表sort()函数调用返回None值的问题求助

Why does 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:12:36