Zone Of Makos

Menu icon

Anonymous Functions in Python

In Python, an anonymous function is a function that is defined without a name. Anonymous functions are also known as lambda functions, because they are defined using the lambda keyword.

Here is an example of an anonymous function:

my_function = lambda x, y: x + y

This lambda function takes two arguments, x and y, and returns their sum. The function can be called like this:

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

Anonymous functions can be useful in a variety of situations, such as:

1. Simple operations

Anonymous functions can be used to define simple operations that don't need to be named. For example, the following anonymous function returns the square of a number:

square = lambda x: x**2

2. Sorting and filtering

Anonymous functions can be used with built-in Python functions like sorted() and filter() to specify a custom sorting or filtering function. For example, the following code uses an anonymous function to sort a list of tuples by the second element:

my_list = [(1, 2), (3, 1), (2, 3)]
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list) # Output: [(3, 1), (1, 2), (2, 3)]

3. Callback functions

Anonymous functions can be used as callback functions, which are functions that are passed as arguments to other functions. For example, the following code uses an anonymous function as a callback function to filter a list:

my_list = [1, 2, 3, 4, 5]
filtered_list = filter(lambda x: x % 2 == 0, my_list)
print(list(filtered_list)) # Output: [2, 4]

Conclusion

Anonymous functions can be a powerful tool in Python, allowing you to define simple functions on the fly without needing to give them a name. However, they can also be harder to read and understand than named functions, especially for more complex operations. Use them judiciously, and always choose the option that makes your code the clearest and easiest to understand.