PEP 289 – Generator Expressions | peps.python.org
pythonpepgenerator-expressionspython-2.4language-design
Abstraction: Python PEP introducing memory-efficient generator expressions in Python 2.4
Key points:
- Generator expressions use syntax
(expr for var in iterable)without brackets, avoiding full list allocation; e.g.sum(x*x for x in range(10)) - Only the outermost for-expression is evaluated immediately; remaining expressions are deferred until generator execution
- Must be directly inside parentheses; when used as the sole argument to a function call, no extra parens needed:
sum(x**2 for x in range(10)) - Loop variable is not exposed to surrounding scope (unlike list comprehensions in Python 2)
- Performance: early timings showed generators faster, but list comprehensions were optimized in Py2.4; generators win at large data volumes by avoiding cache exhaustion
- Authored by Raymond Hettinger, accepted for Python 2.4; reduces need for
itertools.ifilteranditertools.imap
Connections: Python · Raymond Hettinger · Generator Expressions · List Comprehensions