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 generator

()

Going over the values of the generator will empty the generator.

import sys

numbers  = [0, 1, 2, 3, 4, 5, 6]

gn = (n*n for n in numbers)
print(gn)
print(sys.getsizeof(gn))
print()

for num in gn:
    print(num)
print()

gn = (n*n for n in numbers)
squares = list(gn)
print(sys.getsizeof(squares))
print(squares)

print(list(gn)) # the generator was already exhausted

Output:

<generator object <genexpr> at 0x7f8c0bda2930>
120

0
1
4
9
16
25
36

160
[0, 1, 4, 9, 16, 25, 36]
[]