π
Sorting & Searching
sorted/sort Β· key Β· multi-key Β· stability
10. Python Sorting in Practice
Master Python's built-in sort: in-place vs new list, multi-key sorting, reverse, custom key functions, and exploiting the stability guarantee.
sortedkeystable sort
Duration
β± ~45 minutes
Level
π Intermediate
Prerequisite
π― Lecture 9
OUTCOME
Replace any custom comparator with a clean `key=` lambda.
What you'll learn
- 1Distinguish sorted() (new list) from list.sort() (in-place)
- 2Sort by a key function β single, tuple, lambda
- 3Exploit Python's stable sort for multi-pass sorting
Overview
Python's Timsort is O(n log n), stable, and tuned for partially-sorted data. The `key` parameter handles 99% of custom sort needs β you almost never need a comparator.
Core Concepts
1. sorted vs list.sort
python
nums = [3, 1, 4, 1, 5]
# sorted() β returns NEW list
sorted_nums = sorted(nums) # [1, 1, 3, 4, 5]
print(nums) # [3, 1, 4, 1, 5] unchanged
# list.sort() β modifies IN PLACE, returns None
nums.sort() # nums is now sorted
print(nums) # [1, 1, 3, 4, 5]β οΈ
A common bug: `sorted_nums = nums.sort()` β this assigns None to sorted_nums! Use sorted(nums) to get a new list.
2. Reverse
python
sorted(nums, reverse=True) # descending3. key function
python
words = ['banana', 'apple', 'fig']
sorted(words, key=len) # ['fig', 'apple', 'banana']
sorted(words, key=str.lower) # case-insensitive
people = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
sorted(people, key=lambda p: p['age'])
# Sort points by (x, y)
points = [(3,1), (1,2), (3,0)]
sorted(points) # tuples sort lexicographically4. Multi-key sort
python
# Sort by age ascending, then name descending β return a tuple from key
sorted(people, key=lambda p: (p['age'], p['name']))
# For mixed asc/desc directions, exploit stability with two passes
result = sorted(people, key=lambda p: p['name'], reverse=True)
result = sorted(result, key=lambda p: p['age'])
# Result is sorted by age asc, then name desc within each age group5. operator.itemgetter for speed
python
from operator import itemgetter
sorted(records, key=itemgetter(0, 2)) # faster than lambda r: (r[0], r[2])Examples
Example 1 β src/01_basic_sort.py
sorted() vs list.sort() side by side.
Example 2 β src/02_key_func.py
Sort strings by length, by last letter, by lowercase form.
Example 3 β src/03_multi_key.py
Multi-key sort via tuples + the two-pass trick for mixed directions.
Example 4 β src/04_stable_proof.py
Demonstrate that equal keys keep their original order (stability).
Common Mistakes
- `x = list.sort()` assigns None. Use sorted(list) for a new list.
- Sorting with a comparator function β Python 3 only accepts `key=`. Use functools.cmp_to_key as a last resort.
- Mixing types (e.g. sorted([1, 'a'])) β TypeError. Provide a key.
- Forgetting that sorted() builds a new list and uses O(n) extra space.
Recap
- sorted(): new list. list.sort(): in-place, returns None.
- Pass a `key=` function to sort by something derived.
- Tuples enable multi-key sort; stability lets you chain sorts.
Try It
- BOJ 1181 (Word sort) β multi-key.
- BOJ 11650 (Sort points by x then y).
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β