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


Groups > comp.lang.python > #54480

Re: lambda - strange behavior

References <loom.20130920T171549-190@post.gmane.org>
Date 2013-09-21 01:47 +1000
Subject Re: lambda - strange behavior
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.188.1379692080.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

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


Thread

Re: lambda - strange behavior Chris Angelico <rosuav@gmail.com> - 2013-09-21 01:47 +1000

csiph-web