List comprehensions
A list comprehension builds a new list in one line by taking each item from something you can loop over and transforming it.
Used in 114 lessons of the course, from 00.03.
A list comprehension is an expression in square brackets that creates a list. You read it left to right like a sentence: [n * n for n in range(5)] means "n * n for each n in range(5)".
The left part is what goes into the list. The for part says where each item comes from.
It is written this way because the pattern "make an empty list, loop, append" is so common that Python gave it a short form. It reads better, because you see the result and the source on one line.
The course uses it from lesson 00.03, for example squares = [n * n for n in range(1_000_000)]. Read that line the same way: "the square of n for each n in the range". Note that it builds the whole list in memory.
[n * n for n in range(5)]
Reach for it when: you need a new list from another collection, transforming each item with a short expression.
Examples
Common mistake
nums = [1, 2, 3] doubled = [n * 2 for n in nums] print(doubled[3])
Why: The resulting list has 3 items, with indexes 0, 1 and 2. Index 3 does not exist.
How to write it: Use a valid index, such as doubled[2] or doubled[-1] for the last one.
Common mistake
nums = [1, 2, 3] result = [print(n) for n in nums] print(result)
Why: print returns None, so the list fills with None. A comprehension is for building values, not for side effects.
How to write it: If you only want to print, use a regular for loop.
