Python Program to Sort a List of Tuples by the Second Item
Intermediate · Lists
A list of tuples often stores records, such as (name, marks) for each student. By default Python sorts tuples by their first item, so this program passes a key function that tells sorted() to compare the second item, the marks, instead.
Program
Original list: [('Riya', 88), ('Aman', 72), ('Kabir', 95), ('Zoya', 81), ('Meera', 88)]
Sorted by marks, low to high:
Aman 72
Zoya 81
Riya 88
Meera 88
Kabir 95
Sorted by marks, high to low:
Kabir 95
Riya 88
Meera 88
Zoya 81
Aman 72How it works
key=get_marksmakessorted()callget_marks()on every tuple and sort by what it returns, which is the marks.reverse=Truesorts from the highest marks to the lowest.- Riya and Meera both have 88, and they stay in their original order. Python's sort is stable, which means equal items never swap places.
sorted()returns a new list, sostudentsitself is not changed.{name:<6}pads each name to six characters, so the marks line up in a column.
Other ways to write it
Using lambda and itemgetter()
Using lambda: [('Aman', 72), ('Zoya', 81), ('Riya', 88), ('Meera', 88), ('Kabir', 95)]
Using itemgetter: [('Aman', 72), ('Zoya', 81), ('Riya', 88), ('Meera', 88), ('Kabir', 95)]
Ranked: [('Kabir', 95), ('Meera', 88), ('Riya', 88), ('Zoya', 81), ('Aman', 72)]A lambda writes the key function inline. Returning a tuple (-marks, name) sorts by marks from high to low first, then by name to break ties.
Without sorted(), using bubble sort
Sorted by the second item: [('Aman', 72), ('Zoya', 81), ('Riya', 88), ('Kabir', 95)]pairs[j][1] is the second item of the tuple at index j, so the usual bubble sort compares marks instead of whole tuples.
Try it yourself
Sort the same list by name instead, using student[0] in the key function.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Bubble Sort
- Sort a Dictionary by Value
- Sort Strings by Length
- Find Students Who Scored Above 75 Using a Dictionary
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises