Lambda
When a function is defined with the def clause, a variable is assigned to it automatically. So one could assume that the behavior of the functions is different from that of other objects (such as strings and numbers) that can be created and used at the same time (on the fly) without resorting to the creation and definition of variables that contain them.
In Python, functions can also be used on the fly, using a particular syntax called lambda. The functions that are created in this way are called anonymous.
This approach is often used when you want to pass a function as an argument to another function. The lambda syntax requires the lambda clause followed by a list of arguments, a colon character, and the expression to evaluate arguments and finally the inbound value.
Let’s see an example
def foo(f, arg):
return f(arg)
a = foo(lambda x: x*2, 5)
print(a)
if you run it, you get:
>>>
10
The lambda functions however are not as powerful as the functions with the name. These functions can only do operations that can be described by a single expression (equivalent to a line of code).
Lambda functions can be assigned to variables and used as normal functions, but this operation is practically useless since at that point the classic functions can be used.
⇐ Go to Python Lesson 6.1 – Functional Programming
Go to Python Lesson 6.3 – Map and Filter ⇒