Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #25169 > unrolled thread

Re: lambda in list comprehension acting funny

Started byDaniel Fetchinson <fetchinson@googlemail.com>
First post2012-07-11 09:36 +0200
Last post2012-07-11 09:36 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: lambda in list comprehension acting funny Daniel Fetchinson <fetchinson@googlemail.com> - 2012-07-11 09:36 +0200

#25169 — Re: lambda in list comprehension acting funny

FromDaniel Fetchinson <fetchinson@googlemail.com>
Date2012-07-11 09:36 +0200
SubjectRe: lambda in list comprehension acting funny
Message-ID<mailman.2009.1341992176.4697.python-list@python.org>
>>> 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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web