Anonymous Function Python

htt‮www//:sp‬.theitroad.com

In Python, anonymous functions are created using the lambda keyword. They are also known as lambda functions or lambda expressions. An anonymous function is a function that does not have a name and can be defined in a single line of code.

Here's the syntax for defining a lambda function:

lambda arguments: expression

The lambda keyword is followed by the arguments, separated by commas, and then a colon. After the colon, you specify the expression that the function should return. The resulting function is an object that can be assigned to a variable or used as a parameter to another function.

Here's an example of a lambda function that squares its argument:

square = lambda x: x**2
print(square(5))  # Output: 25

In this example, the lambda function takes a single argument x and returns x**2. We assign this function to the variable square, and then call it with the argument 5.

Lambda functions are often used as arguments to other functions, particularly in functional programming. For example, the built-in map() function takes a function and a sequence, and applies the function to each element of the sequence. Here's an example of using a lambda function with map() to double each element of a list:

numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x*2, numbers))
print(doubled_numbers)  # Output: [2, 4, 6, 8, 10]

In this example, we define a lambda function that takes a single argument x and returns x*2. We pass this function as the first argument to map(), along with the list of numbers. The map() function applies the lambda function to each element of the list, and returns a new list with the results. We convert this result to a list using the list() constructor.