How to sort a list in Python
sorted(lst) returns a new sorted list. lst.sort() sorts in place and returns None. Both use Timsort, O(n log n).
nums = [3, 1, 4, 1, 5, 9, 2, 6]
asc = sorted(nums) # new list, ascending
desc = sorted(nums, reverse=True) # new list, descending
nums.sort() # mutates in place
print(nums) # [1, 1, 2, 3, 4, 5, 6, 9]Python's sort is Timsort β a stable O(n log n) algorithm optimised for real-world data with runs of already-ordered elements. Elements are compared with < by default; equal elements stay in their original order (that's what 'stable' means).
For custom sort orders, pass a key= callable. sorted(users, key=lambda u: u['age']) sorts by age. sorted(words, key=len) sorts by string length. This is faster and clearer than a manual cmp_to_key wrap.
sorted() also works on any iterable β sets, dict.items(), generators β and always returns a list.
Variations
Sort by a field
users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
by_age = sorted(users, key=lambda u: u["age"])key= is called ONCE per element (not per comparison) β cheaper than a cmp function.
Sort by multiple fields
by_age_then_name = sorted(users, key=lambda u: (u["age"], u["name"]))Tuple ordering compares element-by-element left to right.
Case-insensitive string sort
words = ["banana", "Apple", "cherry"]
sorted(words, key=str.lower) # ['Apple', 'banana', 'cherry']Pass str.lower as the key β not `str.lower()`.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.