[Tutor] Determining if an iterator has more elements.

Marc Barry marc_barry@hotmail.com
Thu Jul 24 11:19:03 2003


I have read numerous posts in the archive about the following question and I 
haven't been able to find an answer or rather an explanation for the 
following.

I am using iterators in Python but am confused over determining when the 
iterator has no more elements.  Here is a small code snippet to illustrate 
what I am talking about:

a_list = [1,2,3,4,5]

i = iter(a_list)

try:
    while(1):
         print i.next()
except StopIteration:
    pass

Obviously, when you run the above it prints out the values 1, 2, 3...  My 
problem is that the iterator contract in Python causes next() to raise a 
StopIteration exception when there are no further items in the iterator.  
The contract provides no such method to test whether the iterator has more 
elements (i.e. like Java's hasNext()).  Therefore, I using the exception to 
detect when the iterator does not have anymore elements.  I can't think of 
any other way to test for this.  I don't think that exception handling is 
meant to be used to determine when to exit a loop.

I realise that I could do the same thing with the following much simpler 
code:

for i in iter(a_list):
	print i

This though does not add to my understanding of how to handle iterator's 
when not iterating through them with a "for" statement.

Any comments or suggestions on how to test if an iterator has more elements 
(without using the StopIteration exception to do so)?

Marc

_________________________________________________________________
The new MSN 8: advanced junk mail protection and 2 months FREE*  
http://join.msn.com/?page=features/junkmail