4

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?

0

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.