4

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?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Eli Rose
  • 6,788
  • 8
  • 35
  • 55
  • 5
    Relevant: http://programmers.stackexchange.com/questions/112463/why-do-iterators-in-python-raise-an-exception – Alex Riley Nov 07 '15 at 17:05
  • @ajcr: Thanks! I'll look on Programmers first for these kind of questions in the future. This question isn't, I feel, a duplicate of what it is currently marked as a duplicate of, but it is a duplicate of the question at your link (and I am now enlightened). Can we get it changed for posterity? – Eli Rose Nov 08 '15 at 06:00
  • I'm voting to close this question as off-topic because it is about language design, which is better suited (and [already answered](http://programmers.stackexchange.com/questions/112463/why-do-iterators-in-python-raise-an-exception)) on Programmers. – Matt Feb 07 '16 at 10:51

1 Answers1

0

StopIteration is more often used by generator (keyword yield) rather than iterator. Generator uses the exception to indicate to the caller that a sequence has been exhausted.

In addition, taking advantage of exception is an common idiom of python language. A good example is the detection of a float number string. It is commonly written this way in python:

def is_float(in_num):
    try:
        float(in_num)
        return true
    except ValueError:
        return false
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • My impression was that every iterator raises `StopIteration` when it's out of elements. For example, if you execute `it = iter('abc'); next(it); next(it); next(it); next(it)` you get a `StopIteration`. Good point about ask-for-forgiveness, I hadn't considered that. – Eli Rose Nov 08 '15 at 06:05