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
This happens because in Python 3.X, map
objects can be iterated over only once. Pointing multiple iterators at it won't reset it to its starting state.
Compare to map
's behavior in 2.7. It returns a list, so it can be iterated over multiple times.
>>> M = map(abs, (-1, 0, 1))
>>> I1 = iter(M); I2 = iter(M)
>>> print(next(I1), next(I1), next(I1))
(1, 0, 1)
>>> next(I2)
1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.