hasnext() for Python iterators?

The alternative to catching StopIteration is to use next(iterator, default_value).

For example:

>>> a = iter('hi')
>>> print(next(a, None))
h
>>> print(next(a, None))
i
>>> print(next(a, None))
None

This way you can check for None to see if you’ve reached the end of the iterator if you don’t want to do it the exception way.

If your iterable can contain None values you’ll have to define a sentinel value and check for it instead:

>>> sentinel = object()
>>> a = iter([None, 1, 2])
>>> elem = next(a, sentinel)
>>> if elem is sentinel:
...     print('end')
... 
>>>

Leave a Comment