Python Glossary Русский

all Python 3Iterators & generatorsterm

Generator expression

generators

The lazy counterpart of a list comprehension, written in parentheses. It does not build a list in memory.

Syntax

(expr for x in iterable if condition)

A generator expression is single-use: after list(gen) a second pass yields nothing rather than the old values, which is a common cause of a mysterious zero sum. One more subtlety: the leftmost iterable is evaluated immediately when the expression is created, while everything else is deferred, so changing outer variables afterwards still affects the output.

Examples

gen = (x**2 for x in range(5))
print(type(gen))  # → generator
print(list(gen))  # → [0,1,4,9,16]
# Ленивость — память не расходуется
big_gen = (x**2 for x in range(10**6))
print(next(big_gen))  # → 0
print(next(big_gen))  # → 1
# sum с генератором
print(sum(x**2 for x in range(10)))  # → 285
# Фильтрация
evens = (x for x in range(20) if x%2==0)
print(list(evens))  # → [0,2,4,6,8,10,12,14,16,18]
# В функции — скобки не нужны
print(max(len(s) for s in ['hi','hello','ok']))  # → 5
# Вложенный генератор
matrix = [[1,2],[3,4],[5,6]]
flat = (x for row in matrix for x in row)
print(list(flat))  # → [1,2,3,4,5,6]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy