List Comprehensions
The Long Way
You already know how to build a list using a loop. Suppose you want a list of squares for the numbers 1 through 10:
This works perfectly. But Python offers a more compact way to express exactly the same idea — one that reads almost like a mathematical definition.
The List Comprehension
squares = [n ** 2 for n in range(1, 11)]
Same result. One line. The structure is:
[expression for item in iterable]
Read it left to right: "Give me n ** 2, for each n in range(1, 11)."
The expression on the left defines what goes into the new list. The for clause defines where the items come from. Python evaluates the expression once per item and collects the results into a list automatically.
Transforming a List
Comprehensions shine when transforming an existing list into a new one.
No append(), no empty list to initialise. The intent is stated directly: give me the capitalised version of each name.
Filtering With a Condition
You can add an if clause to include only items that meet a condition.
[expression for item in iterable if condition]
Only numbers where n % 2 == 0 make it into the new list. The others are silently skipped.
Filter and transform can be combined in the same comprehension:
This gives a 10% bonus only to scores that already pass. The filtering happens first, then the expression is applied to whatever remains.
When to Use a Comprehension
List comprehensions are ideal when the logic is simple enough to read naturally in one line. The test is straightforward: can you read it aloud and understand it immediately?
# Clear — use a comprehension
evens = [n for n in range(20) if n % 2 == 0]
# Too complex — use a regular loop
results = []
for item in data:
processed = complex_transform(item)
if validate(processed):
results.append(processed)
Comprehensions are a tool for clarity, not a competition to write the shortest code. If it takes longer to read than a loop, write the loop.
A Practical Example
A list of dictionaries — common in real data. The comprehension extracts exactly what you need cleanly, without a five-line loop.
What You Have Learned
List comprehensions are one of Python's most distinctive features — and one of the first things that makes Python feel like Python.
The key ideas:
[expression for item in iterable]builds a new list by applying an expression to each item[expression for item in iterable if condition]filters items before applying the expression- Comprehensions replace the pattern of: create empty list → loop → append
- Use them when the logic fits naturally in one readable line; otherwise use a regular loop
In the next lesson, you'll meet two more collection types — tuples and sets — that solve problems lists cannot.