lambda - strange behavior
Chris Angelico
rosuav at gmail.com
Fri Sep 20 11:47:50 EDT 2013
On Sat, Sep 21, 2013 at 1:21 AM, Kasper Guldmann <gmane at 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
More information about the Python-list
mailing list