Anonymous function
Anonymous function
Anonymous functions in Python are functions that are defined using the `lambda` keyword. Unlike named functions, anonymous functions do not have a specified name. They are often used for simple, one-off operations where defining a full named function is unnecessary or clutters the code.
### Syntax of an Anonymous Function (Lambda Function):
```python
lambda arguments: expression
```
- `lambda`: The keyword used to define an anonymous function.
- `arguments`: The input parameters or arguments.
- `expression`: The operation or calculation the function performs.
### Example of an Anonymous Function:
```python
# Anonymous function to calculate the square of a number
square = lambda x: x ** 2
# Calling the anonymous function
result = square(5)
print("Square:", result) # Output: Square: 25
```
In this example, we define an anonymous function using `lambda` to calculate the square of a number. We then call this anonymous function with the argument `5` and print the result.
### Use Cases for Anonymous Functions:
1. Simple Calculations:
- When you need a quick calculation without defining a named function.
2. Sorting or Filtering:
- In cases where you need to sort or filter data using a custom criterion, anonymous functions can be handy.
```python
data = [(1, 'Alice'), (3, 'Charlie'), (2, 'Bob')]
sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data) # Output: [(1, 'Alice'), (2, 'Bob'), (3, 'Charlie')]
```
3. Callbacks:
- As arguments to higher-order functions that accept functions as parameters.
```python
def apply_operation(operation, x, y):
return operation(x, y)
addition = lambda a, b: a + b
multiplication = lambda a, b: a * b
result_addition = apply_operation(addition, 3, 5)
result_multiplication = apply_operation(multiplication, 3, 5)
print("Addition:", result_addition) # Output: Addition: 8
print("Multiplication:", result_multiplication) # Output: Multiplication: 15
```
Anonymous functions are particularly useful when the function logic is straightforward and does not require a detailed, named function. However, for more complex operations or functions that need to be reused, named functions are generally preferred.
Comments
Post a Comment