In Java, iterators have a hasNext()
method (if I recall correctly -- it's been a long time since I programmed in Java, so the details may be off). When you're stepping through an iterator, you query hasNext()
to see if you should stop.
In Python, there is no hasNext()
, and iterators instead raise the StopIteration
exception when they want to signal that you should stop. Why the difference?
I could imagine that not requiring hasNext()
makes less work for whoever's implementing the iterator; in that case, why do Java and other languages use it? Is it a philosophical difference, or are exceptions for some reason easier/faster in Python?