List comprehensions are a compact way to build lists from an iterable. Instead of creating an empty list and appending in a loop, you write a single expression that describes the resulting list. They are standard Python style for simple “build a list from another” or “filter and transform” tasks. This article covers the syntax, common patterns, and when to prefer them over a regular loop or a generator.
What they are
A list comprehension produces a new list. The basic form is [expression for item in iterable]: for each item in the iterable, expression is evaluated and its value is included in the list. You can add an if clause to filter. For similar ideas with dicts and sets, see Dictionary comprehensions and Set comprehensions.
Basic syntax
Pattern: [expression for item in iterable]
# Loop equivalent:
squares = []
for x in range(5):
squares.append(x ** 2)
# List comprehension:
squares = [x ** 2 for x in range(5)]
# [0, 1, 4, 9, 16]
With a filter: if
Only items that satisfy the condition are included:
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
numbers = [-2, -1, 0, 1, 2, 3]
positive = [x for x in numbers if x > 0]
# [1, 2, 3]
Conditional expression (if-else in the expression)
Use value_if_true if condition else value_if_false when you want to transform each item (not just filter):
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
# ['even', 'odd', 'even', 'odd', 'even']
Nested comprehensions
Useful for lists of lists (e.g. matrices). The inner comprehension runs for each outer item:
matrix = [[i * 3 + j for j in range(3)] for i in range(3)]
# [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
Keep nesting shallow; deep or complex logic is clearer in a normal loop.
When to use them
- Simple transforms or filters: one expression per item, one
ifat most—list comprehensions are readable and idiomatic. - Building a list from a range or iterable: e.g.
[f(x) for x in items]. - Avoid when: logic is multi-step, you need side effects, or the comprehension becomes hard to read—use a
forloop instead. For lazy (memory-efficient) iteration, use a generator or(x for x in ...).
Next steps: Core Concepts · Dictionary comprehensions · Generators · Lists