Search⌘ K
AI Features

Anonymous Functions

Learn to create and use anonymous functions in Python with the lambda keyword. Understand how these single-expression functions differ from regular functions and how they can be called directly or assigned to variables for efficient coding.

Using lambda keyword

An anonymous function is a single-expression function, having no name. The lambda keyword is used to declare the anonymous function. It can have any number of arguments but can have only one expression as stated above. Look at the simple example below and see how an anonymous function works.

x = lambda a: a+5 # anonymous function

The above anonymous function takes one argument a and returns a+5 (single expression).

The above anonymous function is similar to the following regular function defined using the def keyword:

def x(a):
    return a+5

So, the lambda keyword offers us a compact form to declare functions, as compared to the def keyword.

Calling an anonymous function

Run the following program.

Python 3.10.4
x = lambda a: a+5
# Calling anonymous function 'x'
print(x(5))

In the beginning at line 1, we create an anonymous function x taking one argument: a. Look at line 4. We call x just like a normal function and pass 5, and then get 10 as a result.

Surprisingly, it is not necessary to bind an anonymous function with any object. We can also state an expression and call the function at the same line, as follows:

print((lambda a:a+5)(5))

Try running the following executable.

Python 3.10.4
x = lambda a: a+5 # Stating expression
print(x(5)) # Calling function using object
print((lambda a: a+5)(5)) # Stating expression and calling in one line