Reference library

Comprehensions & generators

List/dict/set comprehensions, generator expressions, and lazy iteration.

1 match
Comprehensions & generators easy

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.

sorting list-comprehension generator
Python
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]

# Generat…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Comprehensions & generators — Python code examples

What you will find here

This page collects comprehensions & generators snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.