Sort with Python
Simple sorts · Article 1 of 8 · 3 min read
Start with the tool you will use in real code, so you know what your own versions must match.
The short version
sorted() returns a new sorted list. list.sort() sorts a list in place and returns nothing. Both accept a key function and a reverse flag.
Details
Python sorts with Timsort, which is fast and stable. Stable means items that compare equal keep their original order. You will rely on that later.
Try it yourself
numbers = [5, 2, 9, 1]
print(sorted(numbers))
print(numbers)
numbers.sort(reverse=True)
print(numbers)
You should see [1, 2, 5, 9], then the original [5, 2, 9, 1], then [9, 5, 2, 1].
Explain it to the duck
Why does sorted() leave the original list alone while list.sort() changes it?
Tested with: Python 3.13.