Generators

Generator expressions

List comprehensions build the whole list in memory. Generator expressions look almost identical but produce values on demand. This lesson shows the syntax difference and when laziness pays off.


You already know list comprehensions. Generator expressions look almost the same but produce values one at a time, like a generator function.

A list comprehension builds the whole list straight away:

Python
Output

Swap the square brackets for parentheses and you get a generator expression. Printing it does not show the values, just the object itself:

Python
Output

A list takes up memory for every element. A generator expression only keeps track of where it is, and computes values on demand.

The type confirms it:

Python
Output

When a generator expression is the only argument to a function, you can drop the extra pair of parentheses:

Python
Output

What will be the output?

Python

Conditions work the same way as in list comprehensions:

Python
Output

What will be the output?

Python

Wrap a generator expression with list() when you do want every value:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python