Using generator expressions and comprehensions

We can think of simple generator expressions as an operator with three operands. The syntax for these three operands parallels the for statement:

(expression for target in source)

We specify an expression which is evaluated for each value assigned to a target variable from a source. There are more complex generators, which we'll look at later.

Generator expressions can be used freely in Python. They can be used anywhere in a sequence or a collection that is meaningful.

It's important to note that a generator expression is lazy, or "non-strict." It doesn't actually calculate anything until some consuming operation demands values from it. To see this, we can try to evaluate a generator expression at the ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.