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.

[e(x) for x in s][e(x) \text{ for } x \text{ in } s]new list of e(x)e(x) for each xx in ss
[e(x) for x in s if P(x)][e(x) \text{ for } x \text{ in } s \text{ if } P(x)]only the xx where P(x)P(x) is true

Symbols

e(x)e(x)the expression computed for each xx
ssthe sequence looped over
P(x)P(x)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 for loop written backwards: value first, then for, then optional if.
Practise loops and conditions for free →

← break and continue · Functions and return →

Part of Programming with Python: Loops and conditions.