O'Reilly logo

Python Essentials by Steven F. Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required