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.
Python code
15 linesdata = [("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
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
- Use `operator.itemgetter(1)` from the `operator` module for a faster key function
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.