Anonymous Function in Python with example

I’d be happy to explain anonymous functions (also known as lambda functions) in Python with an example!

In Python, an anonymous function is created using the lambda keyword. It allows you to create a function “on the fly” without having to define a separate named function. The syntax for creating an anonymous function is:

lambda arguments: expression

where arguments is a comma-separated list of parameters, and expression is a single expression that the function will evaluate.

Here’s an example of an anonymous function that takes one argument and returns the square of that argument:

square = lambda x: x ** 2

In this example, lambda x: defines the anonymous function, and x ** 2 is the expression that the function will evaluate. We then assign this anonymous function to the variable square.

We can now call the square function with an argument to get its square. For example:

print(square(4))

This will output 16.

Anonymous functions can be especially useful when you need to define a simple function that you only plan on using once. Instead of defining a named function that you’ll only use once, you can define an anonymous function “on the fly” using lambda.

Leave a Reply