Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: lambda in list comprehension acting funny

Reply
Thread Tools

Re: lambda in list comprehension acting funny

 
 
Daniel Fetchinson
Guest
Posts: n/a
 
      07-11-2012
>>> funcs = [ lambda x: x**i for i in range( 5 ) ]
>>> print funcs[0]( 2 )
>>>
>>> This gives me
>>> 16
>>>
>>> When I was excepting
>>> 1
>>>
>>> Does anyone know why?

>
> Just the way Python lambda expressions bind their variable
> references. Inner 'i' references the outer scope's 'i' variable and not
> its value 'at the time the lambda got defined'.
>
>
>> And more importantly, what's the simplest way to achieve the latter?

>
> Try giving the lambda a default parameter (they get calculated and
> have their value stored at the time the lambda is defined) like this:
> funcs = [ lambda x, i=i: x**i for i in range( 5 ) ]


Thanks a lot!
I worked around it by

def p(i):
return lambda x: x**i
funcs = [ p(i) for i in range(5) ]

But your variant is nicer (matter of taste of course).

Cheers,
Daniel


--
Psss, psss, put it down! - http://www.cafepress.com/putitdown
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
lambda in list comprehension acting funny Daniel Fetchinson Python 45 08-16-2012 12:26 AM
Re: lambda in list comprehension acting funny Daniel Fetchinson Python 4 07-14-2012 10:31 AM
Re: lambda in list comprehension acting funny Jurko Gospodnetić Python 0 07-11-2012 07:01 AM
List comprehension in if clause of another list comprehension Vedran Furac( Python 4 12-19-2008 01:35 PM
Mix lambda and list comprehension? Peter Barth Python 4 07-16-2003 11:20 PM



Advertisments