Comprehensions
Build lists, sets and dicts in a single readable line.
Syntax
[x * 2 for x in numbers if x > 0]A comprehension builds a new collection from an existing one in one compact line. It replaces a loop that appends to a list.
The pattern
[expression for item in iterable if condition]. The if part is optional and filters items.
The same idea works for sets { } and dictionaries {k: v for ...}.
Example
numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers]
print(squares)
evens = [n for n in numbers if n % 2 == 0]
print(evens)
lengths = {w: len(w) for w in ['hi', 'hey']}
print(lengths)
# Output:
# [1, 4, 9, 16, 25, 36]
# [2, 4, 6]
# {'hi': 2, 'hey': 3}When to use it
- A data pipeline squares a list of sensor readings in one compact expression instead of a loop.
- A filter expression builds a list of active users by checking a condition in a list comprehension.
- A lookup table is built as a dict comprehension mapping each word to its character count.
More examples
List comprehension
Creates a new list by squaring each element, then filters to only even numbers.
numbers = [1, 2, 3, 4, 5, 6]
squares = [n ** 2 for n in numbers]
print(squares) # [1, 4, 9, 16, 25, 36]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6]Dict comprehension
Builds a dictionary mapping each word to its length using a dict comprehension.
words = ['apple', 'banana', 'cherry']
length_map = {w: len(w) for w in words}
print(length_map)
# {'apple': 5, 'banana': 6, 'cherry': 6}Set comprehension
Generates unique squared values from a list with duplicates using a set comprehension.
data = [1, 2, 2, 3, 3, 3, 4]
unique_squares = {n ** 2 for n in data}
print(sorted(unique_squares)) # [1, 4, 9, 16]
Discussion