What is the difference between raise StopIteration and a return statement in generators?

There’s no need to explicitly raise StopIteration as that’s what a bare return statement does for a generator function – so yes they’re the same. But no, just using return is more Pythonic.

From: http://docs.python.org/2/reference/simple_stmts.html#the-return-statement (valid to Python 3.2)

In a generator function, the return statement is not allowed to include an expression_list. In that context, a bare return indicates that the generator is done and will cause StopIteration to be raised.

Or as @Bakuriu points out – the semantics of generators have changed slightly for Python 3.3, so the following is more appropriate:

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

Leave a Comment