IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
5.2.5 Generator expressions


5.2.5 Generator expressions

A generator expression is a compact generator notation in parentheses:

Download entire grammar as text.

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.