Global and local variables in lambda expressions
As is the case with
ordinary functions,
variables that are only referenced, but not assigned, in lambda expressions refer to a global variable. The following example creates two lambda expressions that only reference variables: the variable
var
:
val = 2
times_three = lambda: val * 3
squared = lambda: val ** 2
val = 4
print(times_three())
print(squared())
When executed, the script prints
12
16
On the other hand, the following script has an assignment in the lambda expression and hence, the variable v
refers to a variable that is local to the lambda expression:
val = 2
times_three = lambda v=val: v * 3
squared = lambda v=val: v ** 2
val = 4
print(times_three())
print(squared())
When executed, this script prints
6
4