Python Reference ยท Lists, Tuples and Ranges
Python list comprehensions
Reference for Python list comprehensions: the for and if clauses, nested loops, conditional expressions, scope rules, and when a plain loop is better.
A list comprehension builds a new list from any iterable in a single expression. It combines the work of a for loop, an optional filter and an append() call: [expression for item in iterable if condition].
Comprehensions are usually shorter and a bit faster than the equivalent loop, and they make clear that the goal is to build a list. They are best for simple transformations and filters. When the logic needs several statements or becomes hard to read, a regular loop is the better choice.
squares = [n * n for n in range(5)] print(squares) # [0, 1, 4, 9, 16]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
How comprehensions work
Parts of the syntax
[expression for target in iterable] [expression for target in iterable if condition] [expression for a in first for b in second if condition]
The for clause supplies items, each if clause filters them, and the expression computes what goes into the new list. Several for clauses nest in the same order as the equivalent loops: the leftmost is the outer loop.
Filter versus conditional expression
An if at the end removes items. A conditional expression a if test else b at the front chooses a value for every item. They look alike but sit in different places:
- filter:
[n for n in nums if n > 0] - choose:
[n if n > 0 else 0 for n in nums]
Scope
The loop variable lives in the comprehension's own scope and does not leak into the surrounding code (unlike a for statement). The outermost iterable is evaluated once, in the enclosing scope; everything else runs inside the comprehension. An assignment expression (:=) inside a comprehension binds in the enclosing scope.
Related forms
Replace the square brackets to get other results. Curly braces build a set or dict (see dict and set comprehensions). Parentheses make a lazy generator expression that produces items one at a time, which is better when you only need to loop once or feed sum(), any() or max().
Usage notes
- Readability limit. More than two
forclauses, or a long condition, is usually clearer as a loop. - No side-effect loops. Do not use a comprehension only to call a function; it builds a list you throw away.
- Memory. The whole list is built at once. For huge or endless data use a generator expression.
- Order is preserved and duplicates are kept. Wrap in
set()or use a set comprehension to remove duplicates. - Nested comprehensions work, such as a list of lists, but the inner list is rebuilt for each outer item.
- Not a copy tool for nested lists:
[row for row in matrix]copies the outer list only; the inner rows are the same objects. - Comprehensions can contain
awaitinside async functions (asynchronous comprehensions).