A Shorter Way to Build Lists
A list comprehension is a compact, readable way to create a list in one line. It replaces the common pattern of making an empty list and appending inside a for loop.
The long way looks like this:
squares = []
for x in range(1, 4):
squares.append(x * x)
print(squares) # [1, 4, 9]
The comprehension does the same thing in one line:
squares = [x * x for x in range(1, 4)]
print(squares) # [1, 4, 9]
The Basic Shape
Read a comprehension as: the expression, then for each item in a sequence. The expression describes what each new item should be.
print([x for x in range(3)]) # [0, 1, 2]
print([x * 2 for x in [1, 2, 3]]) # [2, 4, 6]
Adding a Condition
You can add an if at the end to keep only items that pass a test. This filters the sequence as it builds the list.
evens = [x for x in range(5) if x % 2 == 0]
print(evens) # [0, 2, 4]
Set and Dictionary Comprehensions
The same idea works with curly braces. A set comprehension builds a set of unique items, and a dictionary comprehension builds key and value pairs.
print({x for x in [1, 1, 2]}) # {1, 2}
print({x: x * x for x in range(3)}) # {0: 0, 1: 1, 2: 4}
Comprehensions can even be nested, though very deep ones become hard to read, so prefer a normal loop when clarity matters more than brevity.
Transforming and Filtering Together
The real power of a comprehension appears when you both change and filter items in one step. The expression on the left decides what to keep, and the condition on the right decides which items qualify.
names = ['ann', 'bo', 'cara']
long_upper = [n.upper() for n in names if len(n) > 2]
print(long_upper) # ['ANN', 'CARA']
Comprehensions are considered good, idiomatic Python because they express a common goal, building a new collection from an old one, in a way that reads almost like a sentence. Use them for short, clear transformations, and switch to a regular loop when the logic grows complicated.
Remember
- A list comprehension builds a list in one line.
- The shape is expression for item in sequence.
- Add an if at the end to filter items.
- Curly braces make set and dictionary comprehensions.
- Choose a plain loop when a comprehension would be hard to read.