Repaso
EspaƱol
PythonIntermediatePY-05

What does this print?

g = (x for x in range(3))
print(list(g), list(g))

Options

  1. [0, 1, 2] [0, 1, 2]
  2. [0, 1, 2] [] (Correct option)
  3. [] []
  4. TypeError

Answer

[0, 1, 2] []

Why

A generator produces values one at a time and does not keep them. Once you have read them all it is 'exhausted' and cannot start again.

The first list(g) reads 0, 1, 2. The second finds nothing left and returns [].

If you need the data twice, store it in a list first.

Remember

Generators are single-use.

Key terms

Practice this question in Repaso