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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With