Anonymous Functions in Python

As the name implies, an anonymous function is a function without an explicit name. It defines a function in a more concise way. Python uses the lambda keyword to create anonymous functions. The syntax is as follows.

code.python
fn = lambda [arg1 [, arg2, ..., argn]]: expression

Here, lambda is a keyword; parameters are declared after it, and the function expression follows the colon. fn can be used as the function name, and the calling format is as follows.

code.python
v = fn(arg1 [, arg2, ..., argn])

Below, we define an anonymous function for multiplying two numbers in the command line.

code.python
>>> rt = lambda a, b: a * b

This function has two parameters, a and b, and the function expression is a * b.

Call the function to calculate and output the product of given data.

code.python
>>> print(rt(2, 5))
10