
Autor: 24.11.2023
Python - Anonymous Functions
In this short article, we'll explain what an anonymous function (lambda) is in the Python language. We'll use a simple example understandable to anyone familiar with the basics of this language.
Definition
An anonymous function in Python, also known as a lambda expression, is a small function defined using the lambda keyword. These functions can take any number of arguments but can only have one expression.
Example
Here's an example of using an anonymous function:
add = lambda x, y: x + y
print(add(2, 3))
The output of the above script is:
5
How does the above script work?
- We create an anonymous function lambda x, y: x + y, which takes two arguments x and y and returns their sum.
- Next, we assign this anonymous function to the variable add.
- After defining the function, we can use it just like any other function. In this case, we call the add(2, 3) function, which returns the sum of 2 and 3, resulting in 5.
- Finally, we output the result of the function's operation, giving us the result 5.
Summary
Anonymous functions are very useful when you need a short-lived function and don't want to define a full function using def. Lambda functions are often used in conjunction with functions such as filter(), map(), and sorted().