From loops to comprehensions
Transforming one list into another is the single most common move in working Python: pull one field out of every record, convert the units on every reading, normalize every string before saving it. Comprehensions are the tool Python added because that pattern shows up everywhere, and they are the first thing reviewers look for when judging whether Python code is fluent.
In Python for Beginners you built lists the long way: start with an empty list, loop, and append each item.
squares = [] for n in [1, 2, 3, 4]: squares.append(n * n)
That pattern is so common that Python has a one-line shortcut for it: the list comprehension. It builds a brand-new list from any sequence you can loop over.
squares = [n * n for n in [1, 2, 3, 4]]
Read it left to right as: build a list of `n n, for each n in this sequence*. Same result, one line, and no empty-list setup or append` call.
The loop and the comprehension side by side
Both versions build the exact same list, so the two printed lines match.
nums = [1, 2, 3, 4, 5] # The loop way, from Python for Beginners squares_loop = [] for n in nums: squares_loop.append(n * n) print(squares_loop) # The comprehension way squares_comp = [n * n for n in nums] print(squares_comp)
Output
[1, 4, 9, 16, 25] [1, 4, 9, 16, 25]
The loop version needs three moving parts: an empty list, a loop header, and an append call. The comprehension folds all three into one expression, and because it is a single expression you can pass it straight into a function call or return it directly.
The expression can be anything
The part before for is a normal Python expression. It runs once per item, and its result lands in the new list. You can call functions, do string work, whatever you like:
names = ["ada", "linus", "grace"] caps = [name.upper() for name in names] # ["ADA", "LINUS", "GRACE"]
Two rules of thumb:
- Use a comprehension when you are transforming every item of a sequence into a new list.
- Keep using a plain
forloop when the body has side effects (printing, saving files) or needs several statements.
Mapping words to their lengths
The value expression does not have to be arithmetic. Any function call works, and len is one of the most common. A single comprehension turns a list of words into a list of word lengths.
words = ["python", "is", "powerful"] lengths = [len(word) for word in words] print(lengths)
Output
[6, 2, 8]
The shape worth memorizing is [SOMETHING for word in words], where SOMETHING is whatever you want each output item to be. Here that slot holds len(word), so the new list has exactly one number per word, in the same order as the input.
Converting a whole list of temperatures
The value expression can also be a full formula. The Celsius to Fahrenheit conversion is f = c × 9/5 + 32, and one comprehension applies it to every reading at once.
temps_c = [0, 10, 25, 30] temps_f = [c * 9 / 5 + 32 for c in temps_c] print(temps_f)
Output
[32.0, 50.0, 77.0, 86.0]
The shape is [EXPRESSION for c in temps_c], and the expression here is c * 9 / 5 + 32. Notice the decimal points in the output. Python's / operator always produces a float, even when the division comes out even, so 0 degrees Celsius arrives as 32.0 rather than 32.
Reading a result at a glance
Evaluating [n + 1 for n in [10, 20, 30]] gives [11, 21, 31]. The expression n + 1 runs once for each item, so every value comes out one larger.
Just as importantly, nothing was appended to the original list. A comprehension always builds a brand-new list and leaves its input untouched, which is why it is safe to run over data you still need in its original form.
When a plain loop is still the right tool
Suppose you need to print a status message for every order as you process it. That is a job for a plain for loop, not a comprehension, because the body exists for its side effect, the printing, rather than to produce a value you keep.
A comprehension has exactly one job: build a new collection out of computed values. Write one purely for side effects and Python still assembles a list out of every print return value, throws it away, and leaves the next reader wondering what that list was supposed to be.
Transforming a sequence into a new collection: reach for a comprehension. Everything else, including printing, saving, and multi-statement bodies: reach for a plain loop.