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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758203004, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/expressions/lambda(79): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78