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:
Swap the square brackets for parentheses and you get a generator expression. Printing it does not show the values, just the object itself:
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:
When a generator expression is the only argument to a function, you can drop the extra pair of parentheses:
What will be the output?
Conditions work the same way as in list comprehensions:
What will be the output?
Wrap a generator expression with list() when you do want every value:
What will be the output?
What will be the output?
What will be the output?
What will be the output?