Python Guide
Python List Comprehension
Write cleaner, faster Python with one-line list transformations.
Quick answer: List comprehension is the Pythonic way to build lists from existing iterables. The syntax is [expression for item in iterable if condition]. It replaces traditional for-loops in one line and is up to 30% faster because the iteration runs in C internally.
The Basic Syntax
A list comprehension has three parts: expression, iteration, and an optional condition.
# Traditional for loop
squares = []
for x in range(5):
squares.append(x ** 2)
# List comprehension (same result)
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
The comprehension reads as: "Give me x ** 2 for each x in range(5)."
Adding a Filter with if
Add an if clause to include only items that match a condition:
# Only even numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Only words longer than 4 characters
words = ["apple", "cat", "banana", "dog", "elderberry"]
long_words = [w for w in words if len(w) > 4]
print(long_words) # ['apple', 'banana', 'elderberry']
Conditional Expression (if-else)
You can also use if-else inside the expression to transform values:
# Label each number as even or odd
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']
💡 Important: When the if-else comes before the for, it transforms values. When if comes after the for, it filters items. Order matters.
Nested Loops in Comprehension
For nested loops, add multiple for clauses:
# Cartesian product
pairs = [(x, y) for x in [1, 2] for y in ["a", "b"]]
print(pairs) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [n for row in matrix for n in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Real-World Examples
Here are patterns you'll use constantly:
# Extract a field from a list of dicts
users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
names = [u["name"] for u in users]
# ['Alice', 'Bob']
# Apply a function to every item
prices = [10.5, 20.99, 5.25]
with_tax = [round(p * 1.08, 2) for p in prices]
# Filter and transform
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
# [4, 16, 36]
# Convert strings to ints
strings = ["1", "2", "3"]
ints = [int(s) for s in strings]
# [1, 2, 3]
Dict and Set Comprehensions
The same syntax works for dictionaries and sets:
# Dict comprehension
squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Set comprehension (removes duplicates)
nums = [1, 2, 2, 3, 3, 3]
unique = {x for x in nums}
# {1, 2, 3}
⚡ Performance: Comprehension vs For Loop
List comprehensions are faster because the loop runs in C internally, not through Python bytecode.
| Method | Relative Speed |
|---|---|
| For loop + append | 1x (baseline) |
| List comprehension | ~1.3x faster |
| Generator expression | Fastest + memory efficient |
🛡️ Best Practices
- Use comprehensions for simple transformations — keep them to one line.
- Add a filter with
ifinstead of a full loop when possible. - Use dict comprehension when building dictionaries from iterables.
- Use generator expressions (parentheses) when the list is large and you only need to iterate once.
- Avoid nesting more than 2 levels deep — readability suffers.
- Don't use comprehensions for side effects (like printing or writing files).
Readability first: A 2-line for loop is better than a 200-character comprehension. If it takes you more than 5 seconds to read, refactor it into a loop.
❓ Frequently Asked Questions
What is list comprehension in Python?
List comprehension is a concise way to create lists in Python. It replaces traditional for-loops with a single-line expression that is both readable and faster.
Is list comprehension faster than a for loop?
Yes. List comprehensions are typically 20-30% faster than equivalent for loops because the iteration is handled internally in C rather than through Python bytecode.
When should I NOT use list comprehension?
Avoid list comprehension when the logic is complex or requires side effects. If the expression becomes hard to read or requires more than 2 conditions, use a regular for loop for clarity.
Can I use list comprehension with dictionaries?
Yes, but for dictionaries you should use dict comprehension: {key: value for item in iterable}. Similarly, set comprehension uses {x for x in iterable}.
What is the difference between list comprehension and generator expression?
List comprehension creates the entire list in memory at once. A generator expression uses parentheses (x for x in iterable) and yields items lazily, saving memory for large datasets.