Has Next in Python Iterators

Kelson Zawack zawackkfb at gis.a-star.edu.sg
Mon Oct 25 12:33:24 CEST 2010


The example I have in mind is list like [2,2,2,2,2,2,1,3,3,3,3] where
you want to loop until you see not a 2 and then you want to loop until
you see not a 3.  In this situation you cannot use a for loop as
follows:

foo_list_iter = iter([2,2,2,2,2,2,1,3,3,3,3])
for foo_item in foo_list_iter:
    if foo_item != 2:
        break
because it will eat the 1 and not allow the second loop to find it.
takeWhile and dropWhile have the same problem.  It is possible to use
a while loop as follows:

foo_list_item = foo_list_iter.next()
while foo_list_item == 2:
    foo_list_item = foo_list_iter.next()
while foo_list_item == 3:
    foo_list_item = foo_list_iter.next()

but if you can't be sure the list is not empty/all 2s then all 3s you
need to surround this code in a try block.  Unless there is a good
reason for having to do this I think it is undesirable because it
means that the second clause of the loop invariant, namely that you
are not off the end of the list, is being controlled outside of the
loop.

As for the feasibly of implementing a has_next function I agree that
you cannot write one method that will provide the proper functionality
in all cases, and thus that you cannot create a has_next for
generators.  Iterators however are a different beast, they are
returned by the thing they are iterating over and thus any special
cases can be covered by writing a specific implementation for the
iterable in question.  This sort of functionality is possible to
implement, because java does it.



More information about the Python-list mailing list