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


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

Re: lambda - strange behavior

Started byChris Angelico <rosuav@gmail.com>
First post2013-09-21 01:47 +1000
Last post2013-09-21 01:47 +1000
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 - strange behavior Chris Angelico <rosuav@gmail.com> - 2013-09-21 01:47 +1000

#54480 — Re: lambda - strange behavior

FromChris Angelico <rosuav@gmail.com>
Date2013-09-21 01:47 +1000
SubjectRe: lambda - strange behavior
Message-ID<mailman.188.1379692080.18130.python-list@python.org>
On Sat, Sep 21, 2013 at 1:21 AM, Kasper Guldmann <gmane@kalleguld.dk> wrote:
> f = []
> for n in range(5):
>     f.append( lambda x: x*n )

You're leaving n as a free variable here. The lambda function will
happily look to an enclosing scope, so this doesn't work. But there is
a neat trick you can do:

f = []
for n in range(5):
    f.append( lambda x,n=n: x*n )

You declare n as a second parameter, with a default value of the
current n. The two n's are technically completely separate, and one of
them is bound within the lambda.

BTW, any time you have a loop appending to a list, see if you can make
it a comprehension instead:

f = [lambda x,n=n: x*n for n in range(5)]

Often reads better, may execute better too.

ChrisA

[toc] | [standalone]


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


csiph-web