Question about exausted iterators

Christophe chris.cavalaria at
Thu May 18 04:18:10 EDT 2006

Terry Reedy a écrit :
> "Christophe" <chris.cavalaria at> wrote in message 
> news:446b48e2$0$5293$626a54ce at
>>Is there a good reason why when you try to take an element from an
>>already exausted iterator, it throws StopIteration instead of some other
>>exception ?
> Yes.
> .
> .
> To distinguish the control message "I am done yielding values, as per the 
> code specification (so don't bother calling me again)." from error messages 
> that say "Something is wrong, I cannot yield values and give up."  In other 
> words, to distinguish expected correct behavior from unexpected incorrect 
> behavior.  This is essential for the normal and correct use of iterators.

You talk about expected behaviour and my expected behaviour is that an 
iterator should not be usable once it has raised StopIteration once.

>>>>>def f(i):
>>...     print list(i)
>>...     print list(i)
>>[0, 1]
> As per specification.

Specifications sometimes have "bugs" too.

> I am guessing that you want the first list() call to terminate normally and 
> return a list, which requires exhausted i to raise StopIteration, while you 
> want the second list() to not terminate but raise an exception, which 
> requires exhausted i to raise something other than StopIteration.  Tough.

Exactly. This would be a sane way to handle it.

> One solution is call list(i) exactly once:
> def f(i):
>     li = list(i)
>     print li
>     print li

Ok, call me stupid if you want but I know perfectly well the "solution" 
to that problem ! Come on, I was showing example code of an horrible 
gotcha on using iterators.

Instead of saying that all works as intended could you be a little 
helpful and tell me why it was intended in such an obviously broken way 
instead ?

More information about the Python-list mailing list