In Python, `sorted(iterable, key=...)` and `list.sort(key=...)` pass each element through the `key` function once to compute a comparison proxy without modifying the original items. To sort tuples by a specific field, pass `key=lambda x: x[1]`; to sort dictionaries by a field, pass `key=lambda d: d['marks']`. Returning a tuple like `(-d['marks'], d['name'])` enables multi-criteria sorting. Both methods use Timsort, guaranteeing stable ordering when keys tie.
- 1. How Python Evaluates the key= Function During Timsort
- 2. Single-Field and Multi-Criteria Tuple Keys
- 3. Sort Stability and operator.itemgetter Alternatives
- 4. Single-Key Tuple Sort and Multi-Criteria Dict Sort
- 5. Common key= Patterns for Tuples and Dictionaries
- 6. Common Mistakes & Top Scorer Tips
- 7. Interactive Concept Check Quiz
- 8. Frequently Asked Questions
1. How Python Evaluates the key= Function During Timsort
By default, sorting a list of tuples compares index `0` first and uses later indices only as tiebreakers, while sorting a list of dictionaries raises a `TypeError` because Python cannot compare two `dict` objects with `<`. Supplying a `key=` callable solves both problems cleanly using a decorate-sort-undecorate pattern. Before reordering, Timsort calls your `key` function exactly once per element—an O(n) step—and stores the computed sort keys alongside the original objects. Comparisons then run on those derived keys rather than the raw tuples or dictionaries. Crucially, the original elements inside the sorted list remain completely intact; the `lambda` only tells Python what value represents each item during ordering. Choose `list.sort()` when in-place mutation is desired and memory matters, or `sorted()` when you need a fresh list while preserving the original input sequence.
- `list.sort()` mutates the list in place and returns `None`; never assign `x = x.sort()`.
- `sorted(seq, key=...)` works on any iterable (tuples, sets, dicts) and always returns a new `list`.
- Sorting dictionaries directly without `key=` triggers `TypeError: '<' not supported between instances of 'dict' and 'dict'`.
2. Single-Field and Multi-Criteria Tuple Keys
Anonymous `lambda` functions shine when extracting a single index or dictionary key inline without cluttering your script with one-off `def` helpers. For a list of `(item_name, price, stock)` tuples, `key=lambda item: item[1]` orders records strictly by `price`. When you need secondary tiebreakers—for instance, ranking records by highest score first and alphabetically by code when scores match—return a tuple from the `lambda`: `key=lambda r: (-r['score'], r['code'])`. Negating numeric values reverses only that numeric field while keeping string tiebreakers ascending, something `reverse=True` alone cannot achieve because `reverse=True` flips every criterion simultaneously. You can also normalize inconsistent casing during comparison using `key=lambda s: s[0].lower()`, ensuring `'apple'` and `'Banana'` sort naturally without altering the stored strings inside the resulting list.
- Return `(-num, text)` in `lambda` to sort numbers descending and strings ascending together.
- Use `d.get('field', 0)` inside `lambda` when optional dictionary keys might be missing.
- Case-insensitive text sorting works via `.lower()` inside `key=` without mutating data.
3. Sort Stability and operator.itemgetter Alternatives
Python's Timsort algorithm is guaranteed to be stable, meaning two elements whose `key` functions produce equal values preserve their original relative order from before the sort. Stability enables a clean multi-pass alternative when descending text sorting is required alongside ascending numbers: first sort by the secondary key, then sort stably by the primary key. In addition, the standard library's `operator.itemgetter` provides a faster C-level replacement for simple index or dictionary-key lambdas, such as `key=itemgetter(1)` for tuples or `key=itemgetter('price')` for dictionaries. While `lambda` remains preferred in CBSE Class 11 and 12 practical files for readability and flexibility with arithmetic expressions like `x[1] * x[2]`, understanding both `itemgetter` and Timsort stability helps you debug subtle tie-breaking behavior in file-handling and SQL-like record processing tasks.
- Timsort preserves input order whenever two items yield equal sort keys.
- Two-pass stable sorting handles mixed ascending/descending string fields cleanly.
- `operator.itemgetter` avoids Python function-call overhead for large record lists.
4. Single-Key Tuple Sort and Multi-Criteria Dict Sort
products = [
("Keyboard", 1200, 15),
("Mouse", 650, 40),
("Monitor", 12500, 8),
("USB Hub", 650, 22),
]
by_price = sorted(products, key=lambda item: item[1])
print("Tuples by price:", by_price)
inventory = [
{"code": "P102", "category": "Audio", "score": 88},
{"code": "P101", "category": "Input", "score": 95},
{"code": "P104", "category": "Display", "score": 88},
{"code": "P103", "category": "Cables", "score": 76},
]
ranked = sorted(inventory, key=lambda r: (-r["score"], r["code"]))
print("Dicts ranked:", [(d["code"], d["score"]) for d in ranked])
Verified Console / Dry-Run Output:
Tuples by price: [('Mouse', 650, 40), ('USB Hub', 650, 22), ('Keyboard', 1200, 15), ('Monitor', 12500, 8)]
Dicts ranked: [('P101', 95), ('P102', 88), ('P104', 88), ('P103', 76)]
5. Common key= Patterns for Tuples and Dictionaries
| Data Structure | Goal | key= Expression | Tiebreaker Behavior |
|---|---|---|---|
| List of tuples | Sort by 2nd element ascending | key=lambda t: t[1] | Preserves input order (stable) |
| List of tuples | Sort by computed total (qty * price) | key=lambda t: t[1] * t[2] | Preserves input order (stable) |
| List of dicts | Highest score first, then code A-Z | key=lambda d: (-d['score'], d['code']) | Breaks score ties using code |
| List of dicts | Case-insensitive name sort | key=lambda d: d['name'].lower() | Preserves order when lowercase matches |
Build Real Python Sorting Confidence
Work through tuple, dictionary, and file-record sorting exercises live with mentors at 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods). Book a free 1:1 trial class.
6. Common Mistakes & Top Scorer Tips
- Avoid Mistake: Writing `nums = nums.sort(key=...)`, which assigns `None` to `nums` because `.sort()` works in place.
- Avoid Mistake: Calling `sorted(dict_list)` without `key=`, raising `TypeError` on dictionary comparisons.
- Avoid Mistake: Passing `reverse=True` when only the numeric score should be descending and the text tiebreaker should stay ascending.
- Examiner / Mentor Tip: Remember that `sorted()` always returns a `list`, even if you pass a tuple of records.
- Examiner / Mentor Tip: Never negate a string inside a `lambda` key (e.g., `-d['name']` raises `TypeError`); use two-pass sorting instead.
- Examiner / Mentor Tip: When fields tie on `key=`, check the original list positions because Python's Timsort preserves their relative order.
7. Interactive Concept Check Quiz
Question: What is the output of sorted([('B', 2), ('A', 2), ('C', 1)], key=lambda x: x[1])?
8. Frequently Asked Questions
Can I sort a dictionary itself by its values using sorted()?
What happens if a key is missing in one dictionary inside the list?
Is a lambda expression allowed to call another function inside key=?
Explore Related Lessons & Free Interactive Tools
- All 110 Guides in CBSE CS (083) & IP (065) Hub
- Python Exception Handling: try-except-else-finally Execution Flow (CBSE 083)
- Using raise, assert, ZeroDivisionError, and Custom Exceptions in Python
- Python random Module Probable Output Questions: randint vs randrange (CBSE 083)
- Interactive Tool: CBSE CS 083 Python Output Predictor Quiz
- Interactive Tool: CBSE SQL GROUP BY / HAVING / JOIN Query Evaluator
