A list comprehension is a compact, one-line way to build a new list by transforming or filtering an existing sequence — instead of writing a multi-line for loop that appends to an empty list, you express the same logic in a single readable expression. It's one of the most distinctly "Pythonic" features in the language.
Basic Syntax: Comprehension vs for Loop
Here's the same task — squaring every number in a list — written both ways, to see exactly what a comprehension replaces:
numbers = [1, 2, 3, 4, 5]
# the traditional for-loop way
squares = []
for n in numbers:
squares.append(n ** 2)
print(squares)
# the equivalent list comprehension
squares_comp = [n ** 2 for n in numbers]
print(squares_comp)
Output:
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
The general shape is [expression for item in iterable] — you write what you want each item transformed into, first.
Filtering with an if Condition
Adding an if at the end of a comprehension filters out items you don't want in the result:
numbers = range(1, 11)
evens = [n for n in numbers if n % 2 == 0]
print(evens)
Output:
[2, 4, 6, 8, 10]
Conditional Expressions Inside a Comprehension
This is a common point of confusion: filtering with a trailing if is different from an inline if...else that changes the value itself. The inline version goes right after the expression, before the for:
numbers = [1, 2, 3, 4, 5, 6]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)
Output:
['odd', 'even', 'odd', 'even', 'odd', 'even']
Notice this version keeps every item (just labels it), while the filtering version removes items entirely. They solve different problems and can even be combined in the same comprehension.
When Not to Use a Comprehension
Comprehensions are great for simple transformations, but once the logic needs multiple conditions, nested loops, or side effects (like printing or logging during the loop), a regular for loop is more readable. A good rule of thumb: if you can't comfortably say the comprehension out loud as one sentence, write it as a loop instead.
