Sort a list of (name, age) tuples by age with sorted() and a lambda key in O(n log n). Learn key functions, stability and operator.itemgetter.
The problem
data is a list of (name, age) tuples. Return it sorted by age, ascending. People with the same age keep their original order.
Examples
Example 1
Input
sort_by_age([('John', 30), ('Alice', 25), ('Bob', 28)])Expected output
[('Alice', 25), ('Bob', 28), ('John', 30)]Example 2
Input
sort_by_age([('A', 2), ('B', 1)])Expected output
[('B', 1), ('A', 2)]
+ 2 hidden tests on Submit — stable on ties.
Edge cases to ask about
- Ties
- Empty list
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| sorted(key=…) | O(n log n) | O(n) | Timsort is stable, so ties keep input order. |
Walkthrough of the optimal approach (try it yourself first)
sorted(data, key=lambda p: p[1]) sorts by the second element. Python's sort (Timsort) is stable, so equal ages keep their original order — that is what makes multi-key sorting by successive sorts possible.
operator.itemgetter(1) does the same and is slightly faster. Use reverse=True for descending.
Complexity: O(n log n) time, O(n) space. Timsort makes O(n log n) comparisons; sorted() returns a new list.
Reveal the reference solution
def sort_by_age(data): return sorted(data, key=lambda person: person[1])
Follow-ups interviewers ask
- Sort by age descending, then name ascending.
- Sort in place with list.sort.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Sort a List of Tuples by Second Element in Python?
The optimal solution runs in O(n log n) time and O(n) auxiliary space. Timsort makes O(n log n) comparisons; sorted() returns a new list.
What follow-up questions do interviewers ask about Sort a List of Tuples by Second Element?
Sort by age descending, then name ascending. Sort in place with list.sort.
