All courses › Programming with Python › List comprehension
List comprehension
A list comprehension builds a new list compactly in one line: [expression for x in sequence]. You can add an if at the end to filter which elements are included.
new list of for each in
only the where is true
Symbols
| the expression computed for each | ||
| the sequence looped over | ||
| filter condition |
Example
[i**2 for i in range(4)] gives [0, 1, 4, 9].
[i for i in range(11) if i % 3 == 0] gives 4 numbers: [0, 3, 6, 9].
Read a list comprehension as an ordinary
Practise loops and conditions for free →
for loop written backwards: value first, then for, then optional if.