Skip to content
TaeyoungKim.dev

Why Python list.sort() Returns None: In-Place Sorting vs. sorted()

PythonWritten 2 min readTaeyoungKim
LinkedInX

You sort three numbers and assign the result to ordered, but it contains None. The original list, meanwhile, is already sorted. The result did not disappear: the confusion is between the list that changed and the value returned.

Why does list.sort() return None?

list.sort() reorders the existing list in place instead of creating a new one. Its return value is therefore not a sorted list.

sort() changes the original list to [1, 2, 3] and returns None. sorted() leaves the original [3, 1, 2] unchanged and returns a new sorted list. Keep the changed list and the return value separate.

python
jobs = [3, 1, 2]
ordered = jobs.sort()

print(ordered)  # None
print(jobs)     # [1, 2, 3]

Running for job in ordered: now raises TypeError: 'NoneType' object is not iterable. This does not mean the list is empty; ordered is not a list at all. If changing the original is the goal, call jobs.sort() without assigning its return value, then use jobs.

Does sorted() change the original list?

Use sorted() when the original order must remain intact. Assign the new list it returns to a variable; the input list stays as it was.

python
jobs = [3, 1, 2]
ordered = sorted(jobs)

print(jobs)     # [3, 1, 2]
print(ordered)  # [1, 2, 3]

An easier way to remember the difference is to ask which list changes. jobs.sort() changes jobs; sorted(jobs) gives you a separate sorted list.

How do you decide whether to change the original?

If other code uses the same list, sorting it in place can have unexpected effects.

python
jobs = [3, 1, 2]
pending = jobs
jobs.sort()

print(pending)  # [1, 2, 3]

pending refers to the same list; it is not a copy. Choose sort() when changing that list is intentional. Choose sorted() when you need to preserve the input order or pass along a separate sorted result. Either way, checking both the return value and the original list quickly explains where the None came from.

Key takeaways

list.sort() sorts a list in place and returns None. sorted() returns a new sorted list without changing the original. Use ordered = sorted(jobs) when you need to assign the result, or jobs.sort() when you want to change jobs itself.

Author

TaeyoungKim

Connecting technical foundations with implementation, verification, and production decisions.

#Python#list.sort#sorted#list sorting#NoneType

Read next