jan
jan

Reputation: 1500

Why is the end of an iteration realized with a StopIteration Exception

When looking at Stackoverflow-Questions about when to raise Exceptions and when to simply return None in Python functions, the emerging picture is that you should use Exceptions for unexpected behaviour and return None otherwise.

However, for-loops over iterables are realized via the StopIteration Exception raised by the next() method, although eventually reaching the "end" of an iterable usually isn't unexpected. Why is the for-loop over iterables implemented the way it is?

Upvotes: 5

Views: 1436

Answers (1)

FunkySayu
FunkySayu

Reputation: 8061

The overall answer is you cannot use sentinel values to safely state the end of an iterator/generator. Imagine simply that you have a list of None objects, None can no longer be used as a sentinel value. That's why StopIteration is used: no sentinel value, the problem is avoided.

If you want to avoid this behavior and return a default value in next, you can simply call next(generator, None).

Upvotes: 8

Related Questions