Mix lambda and list comprehension?

Michele Simionato mis6 at pitt.edu
Wed Jul 16 19:20:46 EDT 2003


bokr at oz.net (Bengt Richter) wrote in message news:<bf3pjm$gsl$0 at 216.39.172.122>...
> On 15 Jul 2003 05:41:02 -0700, mis6 at pitt.edu (Michele Simionato) wrote:
> 
> >peter.barth at t-online.de (Peter Barth) wrote in message news:<6f5b3f88.0307142302.1a1531f3 at posting.google.com>...
> >> Hi,
> >> trying to mix lambda expresions and list comprehension 
> >> doesn't seem to work.
> >> ---
> >> >>> [lambda x:x+y for y in range(10)][9](2)
>  11
> >> >>> [lambda x:x+y for y in range(10)][4](2)
> >> 11
> >> ---
> >> I expected the second expression to return 6.
> >> What did I do wrong? Any hints?
> >> Thanks
> >> - Peter
> >
> >It is a scope issue. The last value for y is used for all
> >the created lambdas. All lambdas users are bitten by that,
> >soon or later. The solution is to make y local to the
> >lambda function, with the optional argument trick:
> >
> >>>> [lambda x,y=y:x+y for y in range(10)][4](2)
> >6
> 
> or you could capture y as constants in the lambdas ;-)
> 
>  >>> [eval('lambda x:x+%s'%y) for y in range(10)][4](2)
>  6
> 
> 
> Regards,
> Bengt Richter

Thanks to God, there is a smile in your post!!

  ;)

       Michele




More information about the Python-list mailing list