Generator expressions

Let's now talk about the other techniques to generate values one at a time.

The syntax is exactly the same as list comprehensions, only, instead of wrapping the comprehension with square brackets, you wrap it with round brackets. That is called a generator expression.

In general, generator expressions behave like equivalent list comprehensions, but there is one very important thing to remember: generators allow for one iteration only, then they will be exhausted. Let's see an example:

# generator.expressions.py>>> cubes = [k**3 for k in range(10)]  # regular list>>> cubes[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]>>> type(cubes)<class 'list'>>>> cubes_gen = (k**3 for k in range(10))  # create as generator>>> cubes_gen

Get Learn Python Programming - Second Edition 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.