Search code examples
pythonlazy-evaluationenumerate

Python bug? Lazy objects have hidden state


Consider this (Python 3.3):

a=enumerate([2,3,5])
print(list(a))
print(list(a))

Do you really expect two print calls to print different things? Neither did I.

The same thing happens if you replace list with set, tuple or dict. It also happens if you replace enumerate object with map or filter, but curiously, not if you replace it with range.

Maybe it is a feature. But it's very surprising, not documented (at least I haven't been able to find anything about it), and not consistent (range works differently). What do you think?


Solution

  • The behaviour is documented at http://docs.python.org/3/glossary.html#term-iterator

    One notable exception is code which attempts multiple iteration passes. ... Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.