How to Sort Data with Comprehensions and Generators in Python

Sort a list of tuples by a key, then use a list comprehension to extract names and a generator to square high ranks.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 13 views 0 copies

Python code

15 lines
Python 3.9+
data = [("Anna", 3), ("Ben", 1), ("Clara", 2), ("Dan", 5), ("Eve", 4)]

# Comprehension: list of tuples (name, rank) sorted ascending by rank
sorted_by_rank = sorted(data, key=lambda x: x[1])

# Comprehension: extract just the names in rank order
names_in_rank_order = [name for name, rank in sorted_by_rank]

# Generator: rank values squared, only for ranks above 2
high_ranks_squared = (rank ** 2 for _, rank in sorted_by_rank if rank > 2)

if __name__ == "__main__":
    print("Sorted list:", sorted_by_rank)
    print("Names:", names_in_rank_order)
    print("Squared high ranks:", list(high_ranks_squared))

Output

stdout
Sorted list: [('Ben', 1), ('Clara', 2), ('Anna', 3), ('Eve', 4), ('Dan', 5)]
Names: ['Ben', 'Clara', 'Anna', 'Eve', 'Dan']
Squared high ranks: [9, 25, 16]

How it works

The sorted() function returns a new list sorted by the key function lambda x: x[1], which picks the second element of each tuple (the rank). A list comprehension [name for name, rank in sorted_by_rank] unpacks each tuple and collects just the names in the sorted order. The generator expression (rank ** 2 for _, rank in sorted_by_rank if rank > 2) lazily computes squared ranks only for ranks above 2, so it avoids building an intermediate list. Converting the generator with list() materializes its values for printing.

Common mistakes

  • Using `data.sort()` instead of `sorted()` which mutates the original list
  • Forgetting to convert a generator to a list before printing or iterating twice
  • Writing the comprehension without unpacking the tuple, e.g. `[x[0] for x in sorted_by_rank]`
  • Filtering ranks with `>= 2` instead of `> 2`, which includes rank 2

Variations

  1. Use `operator.itemgetter(1)` from the `operator` module for a faster key function
  2. Sort descending by adding `reverse=True` to `sorted()`

Real-world use cases

  • Ranking users by score in a leaderboard and extracting their names for display.
  • Processing a config list of (id, priority) pairs where you only need to log tasks above a threshold.
  • Feeding sorted, filtered data into a pipeline without creating large intermediate lists.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.