Editor

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

sort_list_of_tuples.py
students = [("Riya", 88), ("Aman", 72), ("Kabir", 95), ("Zoya", 81), ("Meera", 88)]
def get_marks(student):
return student[1] # the second item of the tuple
low_to_high = sorted(students, key=get_marks)
high_to_low = sorted(students, key=get_marks, reverse=True)
print("Original list:", students)
print("Sorted by marks, low to high:")
for name, marks in low_to_high:
print(f" {name:<6} {marks}")
print("Sorted by marks, high to low:")
for name, marks in high_to_low:
print(f" {name:<6} {marks}")
Output
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   72

How it works

  1. key=get_marks makes sorted() call get_marks() on every tuple and sort by what it returns, which is the marks.
  2. reverse=True sorts from the highest marks to the lowest.
  3. 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.
  4. sorted() returns a new list, so students itself is not changed.
  5. {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 and itemgetter()
from operator import itemgetter
students = [("Riya", 88), ("Aman", 72), ("Kabir", 95), ("Zoya", 81), ("Meera", 88)]
print("Using lambda:", sorted(students, key=lambda s: s[1]))
print("Using itemgetter:", sorted(students, key=itemgetter(1)))
# Highest marks first, and names A to Z when marks are equal
students.sort(key=lambda s: (-s[1], s[0]))
print("Ranked:", students)
Output
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

Without sorted(), using bubble sort
pairs = [("Riya", 88), ("Aman", 72), ("Kabir", 95), ("Zoya", 81)]
n = len(pairs)
for i in range(n - 1):
for j in range(n - 1 - i):
if pairs[j][1] > pairs[j + 1][1]: # compare the second items
pairs[j], pairs[j + 1] = pairs[j + 1], pairs[j]
print("Sorted by the second item:", pairs)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises