Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

List comprehension and Generator Expression

However, before learning about yield let's see an even simpler way to create a generator. What we call a generator expression.

You are probably already familiar with "list comprehensions" where you have a for expression inside square brackets. That returns a list of values.

If you replace the square brackets with parentheses then you get a generator expression.

You can iterate over either of those. So what's the difference?

The generator expression delays the execution of the loop and the expression inside to the point where you actually need the value and it is only an object, not the full list.

So you also save memory.

a_list = [i*2 for i in range(3)]
print(a_list)
for x in a_list:
   print(x)
print()

a_generator = (i*2 for i in range(3))
print(a_generator)
for x in a_generator:
   print(x)

Output:

[0, 2, 4]
0
2
4

<generator object <genexpr> at 0x7f0af6f97a50>
0
2
4