How do list and dictionary comprehensions work in Python?
· Category: Python Programming
Short answer
Comprehensions provide a concise syntax for creating lists, dictionaries, and sets from iterables. They consist of an expression followed by a for clause and optional if filters.
Steps
- Start with the expression for each item.
- Add the
for item in iterableloop. - Append optional
if conditionfilters.
# List comprehension
squares = [x**2 for x in range(10)]
# Dict comprehension
square_dict = {x: x**2 for x in range(5)}
# Set comprehension
square_set = {x**2 for x in range(20)}
Tips
- Comprehensions are generally faster than equivalent
forloops because the iteration happens in C. - Keep comprehensions readable; if they get too complex, use a regular loop or helper function.
- Generator expressions
(x for x in items)are lazy and memory-efficient for large datasets. - Nested comprehensions are possible but can hurt readability.
# Filtering
evens = [x for x in range(20) if x % 2 == 0]
# Nested (matrix transpose)
matrix = [[1, 2], [3, 4], [5, 6]]
transposed = [[row[i] for row in matrix] for i in range(2)]
print(transposed)
Common issues
- Variable leakage in list comprehensions was fixed in Python 3; the loop variable does not leak into the surrounding scope.
- A generator expression must be consumed (e.g., with
list()or a loop) before you can see its values. - Overly complex nested comprehensions can be harder to debug than explicit loops.