an ingrate newbie complains

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Wed Feb 4 21:25:36 EST 2004


> From: Rich Krauter
> 
> Are some of these examples only working because and y have been
> initialized by previous runs?
> I tried deleting x and y between list comprehensions and they 
> don't work anymore.

Indeed.

>>> f = lambda x,y: x*y+2*pow(y,2)
>>> g = lambda x: 3*pow(x,2)
>>> l = [1,2,3,4,5]
>>> [f(x,y) for (x,y) in [(x,g(x)) for x in l] if y>19]
[1539, 4800, 11625]
>>> del x
>>> del y
>>> [f(x,y) for x in l for y in [g(x)] if y>19]
[1539, 4800, 11625]
>>> del x
>>> del y
>>> [f(x,y) for y in [g(x)] if y>19 for x in l]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
>>> [f(x,y) for y in [g(x)] for x in l if y>19]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined

Try expanding them to the non-list comp form and see where the problems are ...

Tim Delaney




More information about the Python-list mailing list