Why does `list.sort()` return `None` instead of the sorted list?
Quick answer
list.sort() sorts the existing list in place and returns None; it is not designed to produce a sorted list as its result. So items = items.sort() replaces the name items with None. Call items.sort() on its own when you want to change that list, or use sorted(items) when you want a new sorted list and need to keep the original unchanged. [S1]
The question, the details, the next step.
A practical checklist
Decide whether the existing list should be changed or kept in its original order.
For an in-place change, call
items.sort()without assigning its result.For a separate sorted list, assign
sorted(items)to a new name.Look for assignments such as
items = items.sort()if a variable unexpectedly becomesNone.
A few more useful answers
Does `items.sort()` leave the list unsorted because it returns `None`?
No. It sorts the existing list in place; None is the method's return value, not a sign that sorting failed. [S1]
How do I get a sorted list without changing the source list?
Use sorted(items) and store its result in another name. It returns a new sorted list and leaves the source unchanged. [S1]
Why does `items` become `None` after `items = items.sort()`?
The assignment stores the value returned by sort(). Since sort() returns None, the name items is rebound to None. [S1]
Sources
References used for this guide.
- [S1] Data Structures — List sorting and return values docs.python.org · Checked
