Question about exausted iterators

Mel Wilson mwilson-to at sympatico.ca
Fri May 19 08:57:03 EDT 2006


yairchu at gmail.com wrote:
> 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.

As an aside, perhaps iter(Y) should be returning a deeper 
copy of Y.  As it stands, I see 'Z=Y' giving the same effect:

 >>> y=iter(x)
 >>> z=iter(y)
 >>> zip(y, z)
[(0, 1), (2, 3)]
 >>> y=iter(x)
 >>> z=y
 >>> zip(y, z)
[(0, 1), (2, 3)]

[ ... ]

> 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:

But the end, raising StopIteration is not where the 
difference is.  The difference is in iter(some_object).

iter(some_container) creates a brand new iterator, standing 
at the starting line and ready to run.

iter(some_listiterator), it seems, just returns a reference 
to some_listiterator, with some of its history possibly 
behind it.

Iterators are used in the same syntactic places as general 
iterables, but especially once people start giving them 
names and handing them around, the real differences show up.

The short-range solution is Know What You're Doing.  Duck 
typing is a fine thing, but it works best for programmers 
who keep scrupulous track of their objects' types.

         Cheers,        Mel.



More information about the Python-list mailing list