| Python Language Reference Manual by Guido van Rossum and Fred L. Drake, Jr. Paperback (6"x9"), 120 pages ISBN 0954161785 RRP £12.95 ($19.95) Sales of this book support the Python Software Foundation! Get a printed copy>>> |
5.2.5 Generator expressions
A generator expression is a compact generator notation in parentheses:
generator_expression "("testgenexpr_for")"genexpr_for "for"expression_list"in"test[genexpr_iter]genexpr_itergenexpr_for|genexpr_ifgenexpr_if "if"test[genexpr_iter]
A generator expression yields a new generator object.
It consists of a single expression followed by at least one
for clause and zero or more for or if
clauses. The iterating values of the new generator are those that
would be produced by considering each of the for or
if clauses a block, nesting from left to right, and
evaluating the expression to yield a value that is reached the
innermost block for each iteration.
Variables used in the generator expression are evaluated lazily
when the next() method is called for generator object
(in the same fashion as normal generators). However, the leftmost
for clause is immediately evaluated so that error produced
by it can be seen before any other possible error in the code that
handles the generator expression.
Subsequent for clauses cannot be evaluated immediately since
they may depend on the previous for loop.
For example: ‘(x*y for x in range(10) for y in bar(x))’.
The parentheses can be omitted on calls with only one argument. See section 5.3.4 for the detail.
| ISBN 0954161785 | Python Language Reference Manual | See the print edition |