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


Groups > comp.lang.python > #25168

Re: lambda in list comprehension acting funny

From Jurko Gospodnetić <jurko.gospodnetic@pke.hr>
Subject Re: lambda in list comprehension acting funny
Date 2012-07-11 09:01 +0200
Organization PKE sistemi d.o.o.
References <CADjSo4QvTnGKy_ZYOO5qZu3tSKovwAMGjku4L+RXEkYmwXPz4g@mail.gmail.com> <CADjSo4SeuMJOP_iEM9rjVsFtVh84HaVUtPkUCZGKiEdQBWuerw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2008.1341990101.4697.python-list@python.org> (permalink)

Show all headers | View raw


   Hi.

>> 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 ) ]


   Hope this helps.

   Best regards,
     Jurko Gospodnetić

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: lambda in list comprehension acting funny Jurko Gospodnetić <jurko.gospodnetic@pke.hr> - 2012-07-11 09:01 +0200

csiph-web