an ingrate newbie complains

Peter Otten __peter__ at web.de
Sat Feb 7 07:58:09 EST 2004


Dan  Dang  Griffith wrote:

> Maybe this should be a new thread, but... is defining a generator
> like I did here, i.e. one that really only returns one value considered
> an abuse of generators?  It sure seemed convenient for this application.
> def g(x): yield 2*x

Now you're asking it - yes, I was a little confused at first. I even removed
the condition to provoke the m x n behaviour of the two for statements,
expecting 100 items in the resulting list - and only then realized n=1.
Also if g() really were something complicated as specified by the OP, you
wouldn't want to limit it to for loops and list comprehensions. This could
be remedied by a little adapter:

>>> def makeGen(f):
...     def g(*x): yield f(*x)
...     return g
...

>>> [(x, y) for x in range(3) for y in makeGen(g)(x)]
[(0, 0), (1, 2), (2, 4)]


However, the resulting code is no longer beautiful, and I'd probably rather
reintroduce a temporary list:

>>> [(x, y) for x in range(3) for y in [g(x)]]
[(0, 0), (1, 2), (2, 4)]

My personal conclusion: use only list comprehensions containing one for,
stick to good old for loops for the more complicated things.

Peter

PS: I mentioned generator expressions as of PEP 289, see
www.python.org/peps/pep-0289.html



More information about the Python-list mailing list