an ingrate newbie complains

Rich Krauter rmkrauter at yahoo.com
Wed Feb 4 21:41:43 EST 2004


I didn't phrase that well. I understand *why* they don't work; I just
meant to point out to OP that it's not an issue with the way iterators
work in python; its because some of the variables referenced in the some
of the list comps had been initialized. So they *appear* to have
unexpected behaviour. In the absence of that accidental initialization,
they don't work at all, as one should expect, since variables are
referenced before they are defined.
Thanks for the suggestion, though.
Rich

On Wed, 2004-02-04 at 21:25, Delaney, Timothy C (Timothy) wrote:
> > 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