Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lambdas and scoping

Tags:

python

lambda

Given this snippet of code:

funcs = []
for x in range(3):
    funcs.append(lambda: x)
print [f() for f in funcs]

I would expect it to print [0, 1, 2], but instead it prints [2, 2, 2]. Is there something fundamental I'm missing about how lambdas work with scope?

like image 487
p-static Avatar asked Dec 17 '09 20:12

p-static


People also ask

What is scope in lambda function?

1 Scope of a Lambda Expression. The body of a lambda expression has the same scope as a nested block. The same rules for name conflicts and shadowing apply. It is illegal to declare a parameter or a local variable in the lambda that has the same name as a local variable.

What is scoping in Python?

A variable is only available from inside the region it is created. This is called scope.

Are lambdas Pythonic?

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument.

Are lambdas faster Python?

Lambda functions are inline functions and thus execute comparatively faster. Many times lambda functions make code much more readable by avoiding the logical jumps caused by function calls.


1 Answers

This is a frequent question in Python. Basically the scoping is such that when f() is called, it will use the current value of x, not the value of x at the time the lambda is formed. There is a standard workaround:

funcs = []
for x in range(10):
funcs.append(lambda x=x: x)
print [f() for f in funcs]

The use of lambda x = x retrieves and saves the current value of x.

like image 153
Kathy Van Stone Avatar answered Oct 07 '22 15:10

Kathy Van Stone