Comprehensions
Comprehensions are a compact way to build new collections from existing data. They help you express a loop, an optional filter, and a transformation in a single expression when the logic stays simple.
Why They Exist
Section titled “Why They Exist”Without a comprehension, you usually write a loop, an optional condition, and an append step.
result = []for x in range(10): if x % 2 == 0: result.append(x**2)The same idea in one line:
result = [x**2 for x in range(10) if x % 2 == 0]Core Idea
Section titled “Core Idea”- A comprehension combines a loop, a filter, and a result expression
- It removes repeated setup code
- It works best when the transformation is easy to read at a glance
General Syntax
Section titled “General Syntax”[expression for item in iterable if condition]Parts of the Syntax
Section titled “Parts of the Syntax”| Part | Meaning |
|---|---|
expression | What to generate |
item | Current element |
iterable | Source collection |
condition | Optional filter |
How It Runs
Section titled “How It Runs”List Comprehension
Section titled “List Comprehension”List comprehensions build a new list from an iterable.
squares = [x**2 for x in range(10)]With a Filter
Section titled “With a Filter”even_squares = [x**2 for x in range(10) if x % 2 == 0]Equivalent Loop
Section titled “Equivalent Loop”even_squares = []for x in range(10): if x % 2 == 0: even_squares.append(x**2)Multiple Loops
Section titled “Multiple Loops”pairs = [(x, y) for x in range(2) for y in range(2)]# Output: [(0, 0), (0, 1), (1, 0), (1, 1)]Inline Choice
Section titled “Inline Choice”labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]Set Comprehension
Section titled “Set Comprehension”Set comprehensions build a set, so duplicate values are removed automatically.
unique_squares = {x**2 for x in range(10)}Good Uses
Section titled “Good Uses”- Removing duplicate values
- Building a quick lookup set
nums = [1, 2, 2, 3]unique = {x for x in nums} # {1, 2, 3}Dictionary Comprehension
Section titled “Dictionary Comprehension”Dictionary comprehensions create key-value pairs from an iterable.
square_dict = {x: x**2 for x in range(5)}With a Filter
Section titled “With a Filter”filtered = {x: x**2 for x in range(10) if x % 2 == 0}Example
Section titled “Example”words = ["apple", "banana", "cherry"]length_map = {word: len(word) for word in words}Generator Expressions
Section titled “Generator Expressions”Generator expressions use round brackets instead of square brackets. They produce values one by one instead of building the full result at once.
gen = (x**2 for x in range(10))Main Difference
Section titled “Main Difference”- List comprehensions create the full list immediately
- Generator expressions create items only when needed
for value in gen: print(value)Memory Use
Section titled “Memory Use”Why They Are Often Faster
Section titled “Why They Are Often Faster”1. Less Python-level overhead
Section titled “1. Less Python-level overhead”- A loop usually performs several repeated steps in Python
- A comprehension keeps that pattern tighter and simpler for the interpreter
2. Fewer repeated operations
Section titled “2. Fewer repeated operations”# loop styleresult.append(x)
# comprehension style[x for x in iterable]3. Cleaner scope handling
Section titled “3. Cleaner scope handling”The variable used inside a comprehension does not leak into the outer scope.
Performance Example
Section titled “Performance Example”# Loopresult = []for x in range(1000000): result.append(x)
# Comprehensionresult = [x for x in range(1000000)]For simple transformations, the comprehension is usually shorter and often faster.
When to Use Them
Section titled “When to Use Them”- The logic is short and direct
- You are transforming or filtering one iterable into another
- The result fits naturally into a single expression
Avoid Them When
Section titled “Avoid Them When”- The logic has many branches
- You need several nested conditions
- A normal loop would be easier to read and debug
Readability Example
Section titled “Readability Example”This is too crowded for a comprehension:
result = [x*y for x in range(10) for y in range(10) if x % 2 == 0 if y % 3 == 0]The loop version is easier to scan:
result = []for x in range(10): if x % 2 != 0: continue for y in range(10): if y % 3 == 0: result.append(x*y)Scope Behavior
Section titled “Scope Behavior”x = 10lst = [x for x in range(5)]
print(x) # 10Nested Comprehensions
Section titled “Nested Comprehensions”matrix = [[i*j for j in range(3)] for i in range(3)]Output
Section titled “Output”[ [0, 0, 0], [0, 1, 2], [0, 2, 4],]Real-World Use Cases
Section titled “Real-World Use Cases”Filtering Data
Section titled “Filtering Data”users = [{"active": True}, {"active": False}]active_users = [u for u in users if u["active"]]Data Transformation
Section titled “Data Transformation”prices = [100, 200, 300]discounted = [p * 0.9 for p in prices]Flattening Lists
Section titled “Flattening Lists”matrix = [[1, 2], [3, 4]]flat = [num for row in matrix for num in row]