hasNext in Python iterators?

Juanjo Conti picture Juanjo Conti · Dec 27, 2009 · Viewed 146.1k times · Source

Haven't Python iterators got a hasNext method?

Answer

Derrick Zhang picture Derrick Zhang · Mar 25, 2013

There's an alternative to the StopIteration by using next(iterator, default_value).

For exapmle:

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

So you can detect for None or other pre-specified value for end of the iterator if you don't want the exception way.