Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static behavior of iterators in Python

I am reading Learning Python by M.Lutz and found bizarre block of code:

>>> M = map(abs, (-1, 0, 1))
>>> I1 = iter(M); I2 = iter(M)
>>> print(next(I1), next(I1), next(I1))
1 0 1
>>> next(I2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Why when I call next(I2) it happens that iteration is already over? Didn't I create two separate instances of I1 and I2. Why does it behave like an instances of a static object?

like image 498
Rudziankoŭ Avatar asked Dec 24 '22 07:12

Rudziankoŭ


1 Answers

This has nothing to do with "static" objects, which don't exist in Python.

iter(M) does not create a copy of M. Both I1 and I2 are iterators wrapping the same object; in fact, since M is already an iterator, calling iter on it just returns the underlying object:

>>> iter(M)
<map object at 0x1012272b0>
>>> M
<map object at 0x1012272b0>
>>> M is iter(M)
True
like image 159
Daniel Roseman Avatar answered Jan 05 '23 20:01

Daniel Roseman