Sorting with key functions
Sorting by one field is easy. Real questions sort by several fields, some up and some down, with missing values mixed in. This lesson shows how Python sorts with a key function, why its sort is stable, and how those two facts solve every awkward ordering.
Foundations · Python for data engineers · Bronze · Everyday idioms, lesson 1 of 3
On this page
Read first: Lists, dicts and sets: what each operation costs (skip if you know it)
In plain words first
Imagine sorting a pile of exam papers. You do not compare whole papers; you look at one thing on each, the score, and order by that. If two papers have the same score, you then look at a second thing, the name.
In Python, the "thing you look at" is the key function, and "score, then name" is a key that returns a tupletuple: An ordered, immutable sequence like ("Pune", 2026). Because it cannot change, it can be a dict key; use it for small fixed records. Learn more →. Everything in this lesson is a way of writing that key.
sorted and list.sort
sorted(iterable) returns a new list and works on anything iterableiterable: Anything you can loop over with for: a list, a string, a dict, a range, a file. Calling iter() on it gives a fresh iterator. Learn more →; my_list.sort() sorts a list in place and returns None. Both take the same key and reverse arguments and run in O(n log n).
tips = [30, 10, 20] print("sorted(tips):", sorted(tips), "| tips unchanged:", tips) result = tips.sort() print("tips.sort() returned:", result, "| tips is now:", tips)
Output from a real run
sorted(tips): [10, 20, 30] | tips unchanged: [30, 10, 20] tips.sort() returned: None | tips is now: [10, 20, 30]
Key functions
key is a function applied to each element; elements are ordered by what it returns. To sort by several fields, return a tuple: tuples compare element by element, so the first field decides and later ones break ties.
riders = [ {"name": "Kiran", "city": "Pune", "rating": 4.6}, {"name": "Arun", "city": "Goa", "rating": 4.9}, {"name": "Meera", "city": "Pune", "rating": 4.8}, ] by_city = sorted(riders, key=lambda r: (r["city"], r["rating"])) for r in by_city: print(r["city"], r["rating"], r["name"])
Output from a real run
Goa 4.9 Arun Pune 4.6 Kiran Pune 4.8 Meera
Some keys up, some down
reverse=True flips the whole tuple. For a numeric field that should go high to low while the rest go low to high, negate it inside the key. For text that must go Z to A, use stability instead (below).
riders = [("Kiran", 4.8), ("Arun", 4.9), ("Meera", 4.8)] # r[1] is the rating, r[0] the name; -4.9 sorts before -4.8 ranked = sorted(riders, key=lambda r: (-r[1], r[0])) print(ranked)
Output from a real run
[('Arun', 4.9), ('Kiran', 4.8), ('Meera', 4.8)]Stability: sorting in passes
Python's sort is stable: elements that compare equal keep their original order. So you can sort by the least important key first and the most important last, each with its own direction. It also means "sort by date, keep arrival order for ties" needs no extra key.
rows = [("Meera", "Pune"), ("Arun", "Goa"), ("Kiran", "Pune")] rows.sort(key=lambda r: r[0]) # pass 1: name A to Z rows.sort(key=lambda r: r[1], reverse=True) # pass 2: city Z to A, ties keep pass 1 print(rows)
Output from a real run
[('Kiran', 'Pune'), ('Meera', 'Pune'), ('Arun', 'Goa')]Sorting data that contains None
Comparing None with a number raises TypeError. Sort by a pair instead: (x is None, x or 0). A real rating gets False first and a missing one gets True, and False sorts before True, so the Nones go last. The second part, x or 0, gives None a stand-in number so two pairs can always be compared.
ratings = [4.5, None, 3.9, None, 4.8] for x in ratings: print(x, "->", (x is None, x or 0)) print(sorted(ratings, key=lambda x: (x is None, x or 0)))
Output from a real run
4.5 -> (False, 4.5) None -> (True, 0) 3.9 -> (False, 3.9) None -> (True, 0) 4.8 -> (False, 4.8) [3.9, 4.5, 4.8, None, None]
Common mistakes
- reverse=True with a tuple key — It reverses every field. Negate the one numeric field instead.
- x = my_list.sort() — sort() returns None. Use sorted() when you need the result.
- Sorting lists that contain None — TypeError. Put (x is None) first in the key.
Key takeaways
- sorted returns a new list; list.sort sorts in place and returns None.
- A tuple key sorts by several fields in order.
- Negate numeric fields to mix directions; reverse flips everything.
- Sorting is stable: equal keys keep their order.
Interview prep
THE QUESTION
"How do you sort records by salary descending, then name ascending?"
sorted(rows, key=lambda r: (-r.salary, r.name)). reverse=True would also reverse the names. If the descending field were a string, I would rely on stability and sort twice: first by name ascending, then by the other field with reverse=True.Avoid: "I use reverse=True for the descending field". With a tuple key it reverses every field.
Follow-ups · answer out loud, then open
Follow-up"What does it mean that Python's sort is stable, and why is it useful?"
Scenario"Sort 50 million log records by timestamp on one machine."
Trap"sorted() on a list with None values puts the Nones first."
Check yourself
3 questionsWhat does [3, 1, 2].sort() return?
Show the answer
None. list.sort sorts in place and returns None.
key=lambda r: (-r[1], r[0]) sorts by...
Show the answer
r[1] descending, r[0] ascending. Negating the number reverses its direction only.
Why can you sort by several keys in separate passes?
Show the answer
Python sorts are stable. Ties keep the order the previous pass produced.
Practise this
Problems that use this, graded on hidden tests
- Sort by Several KeysCore Python & data structures Medium
- Group AnagramsDSA for data engineers Medium
- Top K Frequent with a HeapDSA for data engineers Medium
Keep going
Up next · Everyday idioms · lesson 2 of 3 · 4 min readMutability, copies and default arguments
What assignment really does, shallow versus deep copies, and the mutable default trap.
Related lessons
Heaps, top-k and k-way mergesPython for data engineers · 6 min read
Counter, defaultdict and deque
Previous: Counter, defaultdict and deque
Primary sources: Sorting HOW TO