A generator expression is a compact generator notation in parentheses:
generator_expression | ::= | "(" test genexpr_for ")" |
genexpr_for | ::= | "for" expression_list "in" test [genexpr_iter] |
genexpr_iter | ::= | genexpr_for | genexpr_if |
genexpr_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.
See About this document... for information on suggesting changes.