Question about exausted iterators

yairchu at gmail.com yairchu at gmail.com
Fri May 19 07:32:53 EDT 2006


Consider this example:

>>> X = range(5)
>>> Y = iter(X)
>>> Z = iter(Y)

As you can see, X is a container, and Y is an iterator.
They are simliar in that "iter" works on them both.

Cristoph claims that this causes confusion.
Why? Because "iter" doesn't have the same meaning for both of them.
For X it always returns an iterator that yields the same set of values.
For Y it returns an iterator yielding different values each time.

>>> Z = iter(Y)
>>> Z.next()
0
>>> Z = iter(Y)
>>> Z.next()
1

Most of the uses of iterators iterate all values until exaustion.
Given that, the first call to "iter" will mean the same for an iterator
and a container, but the second one won't.

Allow me to compare it to division in python 2.4
>>> 4./2, 4/2
2.0, 2
>>> 5./2, 5/2
2.5, 2

Division sometimes works the same for integers and reals, and sometimes
doesn't.
This caused consfusion and bugs, and that's why future Pythons will
change that.

But changing "iter" to have the same meaning for containers and
iterables is impossible.
You cannot, conceptually, reiterate an iterator.
So what Cristoph is suggesting - is to add an exception for the cases
in which iterators and collections behave differently.
Somewhat similar to this:

>>> 4/2
2
>>> 5/2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IntegerDivisionError: 5 does not divide by 2




More information about the Python-list mailing list