Comprehensions
What is a comprehension?
Section titled “What is a comprehension?”A comprehension is a concise, readable expression that builds a new collection by transforming or filtering an iterable. Python provides three forms: list, dict, and set comprehensions.
List comprehensions
Section titled “List comprehensions”The general form is:
[expression for item in iterable][expression for item in iterable if condition]squares = [x**2 for x in range(1, 8)]# [1, 4, 9, 16, 25, 36, 49]
evens = [x for x in range(20) if x % 2 == 0]# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]Both examples are equivalent to a for loop that appends to a list — but they are more compact and typically faster because the iteration happens in C rather than bytecode.
Nested comprehensions
Section titled “Nested comprehensions”You can nest multiple for clauses to iterate over combinations.
The clauses are read left to right — the leftmost for is the outer loop.
pairs = [ (x, y) for x in range(1, 4) for y in range(1, 4) if x != y]# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]Dict comprehensions
Section titled “Dict comprehensions”Wrap the expression in {} and use key: value syntax.
word_len = {word: len(word) for word in ['apple', 'banana', 'cherry']}# {'apple': 5, 'banana': 6, 'cherry': 6}Dict comprehensions are a clean way to invert a mapping, filter entries, or transform values:
prices = {'apple': 1.5, 'banana': 0.75, 'cherry': 3.0}expensive = {k: v for k, v in prices.items() if v >= 1.5}# {'apple': 1.5, 'cherry': 3.0}Set comprehensions
Section titled “Set comprehensions”Same syntax as list comprehensions but with {}.
Duplicates are automatically discarded.
unique_lens = {len(word) for word in ['apple', 'banana', 'cherry', 'date']}# {4, 5, 6} (order not guaranteed)Full runnable demo
Section titled “Full runnable demo”# --- list comprehension ---squares = [x**2 for x in range(1, 8)]print('squares:', squares)
evens = [x for x in range(20) if x % 2 == 0]print('evens:', evens)
# --- nested comprehension ---pairs = [(x, y) for x in range(1, 4) for y in range(1, 4) if x != y]print('pairs:', pairs)
# --- dict comprehension ---word_len = {word: len(word) for word in ['apple', 'banana', 'cherry']}print('word lengths:', word_len)
# --- set comprehension ---unique_lens = {len(word) for word in ['apple', 'banana', 'cherry', 'date']}print('unique lengths:', sorted(unique_lens))Loading Python runtime (first run only)…