Sort a list of tuples by 2nd item integer value
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Sorting a list of tuples by the second element is a very common Python task, especially when each tuple represents a name-value pair, a record key plus score, or some other lightweight structure. The clean solution is to give Python a key function that extracts index 1, which is the second item in each tuple.
The Basic sorted Solution
Python's built-in sorted function accepts a key argument. That function is called for each item, and the returned value is what Python uses to order the list.
Output:
The lambda lambda item: item[1] means "use the second element of each tuple as the sort key."
sorted Versus list.sort
Python gives you two closely related choices:
- '
sorted(...)returns a new list' - '
list.sort(...)sorts the existing list in place'
Example with in-place sorting:
Use sorted when you want to preserve the original list. Use sort when mutating the list is acceptable and you do not need a separate copy.
A Slightly Cleaner Key Function
For this exact pattern, operator.itemgetter is often a little cleaner than a lambda.
This does the same thing as lambda item: item[1], but some readers find it easier to scan.
Descending Order
If you want the largest integer first, add reverse=True.
Output:
Stability Matters
Python sorting is stable. That means if two tuples have the same second value, their original relative order is preserved.
Output:
"alice" stays ahead of "carol" because both have the same sort key and Python does not scramble ties unnecessarily.
Sorting by Multiple Fields
Sometimes the second item is the main key, but you also want a tie-breaker. In that case, return a tuple of keys.
This sorts first by the integer in position 1, then by the string in position 0 when the integers match.
Common Pitfalls
The biggest mistake is using the wrong index. Tuple index 1 is the second item, while tuple index 0 is the first.
Another issue is forgetting that list.sort(...) returns None. If you write result = items.sort(...), result will not contain the sorted list.
Developers also sometimes mix incomparable types in the second tuple position. Sorting works cleanly only when the extracted keys can be compared consistently.
Finally, choose between sorted and sort deliberately. One returns a new list, the other mutates the original.
Summary
- Use
sorted(items, key=lambda item: item[1])to sort by the second tuple element. - Use
items.sort(...)if you want to sort the list in place. - '
operator.itemgetter(1)is a concise alternative to a lambda.' - Add
reverse=Truefor descending order. - Python sorting is stable, so equal keys keep their original relative order.

