Python Glossary Русский

all Python 3Lists (list)function

List comprehensions

comprehension

Compact syntax for building a list, with optional filtering. Faster than the equivalent for+append loop.

Syntax

[expr for var in iterable [if cond]]

The loop variable is local to the comprehension and never leaks out, so a same-named name outside keeps its value. Nested for clauses read left to right exactly like nested loops, and the whole list is materialised at once — for large or endless streams use a generator expression in parentheses instead.

Examples

squares = [x**2 for x in range(6)]
print(squares)
# → [0, 1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
# → [0, 2, 4, 6, 8]
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs)
# → [(1, 3), (1, 4), (2, 3), (2, 4)]
words = ['hello', 'world', 'python']
upper = [w.upper() for w in words]
print(upper)
# → ['HELLO', 'WORLD', 'PYTHON']
flat = [x for row in [[1,2],[3,4],[5,6]] for x in row]
print(flat)
# → [1, 2, 3, 4, 5, 6]
mapped = [x if x > 0 else 0 for x in [-1, 2, -3, 4]]
print(mapped)
# → [0, 2, 0, 4]
digits = [int(c) for c in '12345']
print(digits)
# → [1, 2, 3, 4, 5]
nested = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(nested)
# → [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy