Why doesn't StopIteration get caught in the following code?

Terry Reedy tjreedy at udel.edu
Sun Apr 5 04:48:18 CEST 2009

grocery_stocker wrote:
>>>> while True:
> ...    i = gen.next()
> ...    print i
> ...
> 0
> 1
> 4
> Traceback (most recent call last):
>   File "<stdin>", line 2, in ?
> StopIteration

If you had written

for item in gen: print(i)

then StopIteration from gen would be caught.

One expansion of a for loop is (in the above case)

it = iter(gen) # not needed here, but is for general iterables
   while True:
     i = it.next()
     print(i) # or whatever the loop body is
except StopIteration:

In other words, 'for i in iterable' expands to several lines of 
boilerplate code.  It is very useful syntactic sugar.

You left out the try..except part.

More information about the Python-list mailing list