Search notes:

Python: lambda

type of a lambda expression

The type of a lambda expression is function:
>>> type(lambda x: x*2)
<class 'function'>

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())
Github repository about-Python, path: /expressions/lambda/global-vars.py
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())
Github repository about-Python, path: /expressions/lambda/assign-vars.py
When executed, this script prints
6
4

See also

The built-in functions filter() and map().

Index