top of page

Python Anonymous Function

In Python, an anonymous function is a function that is defined without a name. It is also known as a lambda function because it is created using the `lambda` keyword. Anonymous functions are typically used when you need a simple function that is used once and doesn't require a formal definition.


The syntax of an anonymous function in Python is as follows:



lambda arguments: expression

Here, `arguments` represents the input parameters of the function, and `expression` is the operation or calculation that the function performs. The result of the expression is automatically returned by the lambda function.


Here's an example that demonstrates the use of an anonymous function to calculate the square of a number:



square = lambda x: x ** 2

result = square(5)
print(result)  # Output: 25

In this example, the lambda function `lambda x: x ** 2` takes an argument `x` and returns the square of `x`. The result is assigned to the variable `square`, and then the lambda function is called with the argument `5`, resulting in the value `25`.


Anonymous functions can also take multiple arguments. Here's an example that adds two numbers using an anonymous function:



add = lambda a, b: a + b

result = add(2, 3)
print(result)  # Output: 5

In this case, the lambda function `lambda a, b: a + b` takes two arguments `a` and `b` and returns their sum.


Anonymous functions are commonly used in combination with other functions or methods that expect a function as an argument. For example, the `map()` function can be used with an anonymous function to apply the same operation to each element of an iterable:



numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))

print(squared_numbers)  # Output: [1, 4, 9, 16, 25]

In this example, the `lambda x: x ** 2` function is passed as the first argument to the `map()` function, which applies the lambda function to each element of the `numbers` list, resulting in a new list of squared numbers.


Anonymous functions provide a concise and convenient way to define simple functions on the fly without the need for a formal function definition. However, they are best suited for small, single-use functions, and for more complex functionality, it's often better to use named functions.

Related Posts

See All

Mastering Lists in Python

Introduction Lists are one of the most fundamental and versatile data structures in Python. They allow you to store and manipulate collections of items, making them an essential tool for any Python pr

Python Inheritance

Like any other OOP languages, Python also supports the concept of class inheritance. Inheritance allows us to create a new class from an existing class. The new class that is created is known as subcl

コメント


bottom of page