Language Syntax

Generator expression — Python syntax

Construct a generator that produces values lazily. The leftmost iterable expression is evaluated immediately; later clauses and result expressions run during iteration. A generator is consumed once. Parentheses can be omitted when it is the sole argument in a call.

Formal Syntax & Structure

python syntaxpython
(expression for target in iterable if condition)

Parameters & Attributes

NameTypeDescription
expressionexpressionValue computed when iterated.
targetassignment targetIteration target.
iterableexpressionSource iterable.
conditionexpressionOptional filter.

Return Value

generator

Value obtained by evaluating this expression; see description for context and constraints.

Working Example

Example Snippetpython
g=(x*x for x in range(3))print((next(g), list(g), list(g)))
Python Reference