[Python-ideas] for/else syntax

Gerald Britton gerald.britton at gmail.com
Fri Oct 2 16:03:12 CEST 2009

> Footnotes:
> [1]  StopIteration can, but I thought raising StopIteration in user
> code is considered quite bad form.

StopIteration once put forward on this very list as a way to stop a
generator. e.g.

def stop():
  raise StopIteration

gen = (x in something if <x meets some condition> or stop() )

Toy example:

Say you want the squares of all natural numbers n such that n <= j.
Here's one simple way using the stop function above:

from itertools import count

squares = (n**2 for n in count() if n <= j or stop() )

Without the "or stop()" the generator goes into an infinite loop when
n exceeds 10.  Of course you can do this toy example other ways, this
is just an illustration.

> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

Gerald Britton

More information about the Python-ideas mailing list