In Python, a lambda function is a concise way to create anonymous functions. It is often used for short, simple operations. Here's an explanation with examples:
1. Basic Lambda Function:
```python
add = lambda x, y: x + y
result = add(3, 5)
print(result)
```
In this example, the lambda function takes two parameters `x` and `y` and returns their sum. The result is assigned to the variable `result`.
2. Lambda with Map:
```python
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
```
Here, the lambda function is used with the `map` function to square each element in the `numbers` list.
3. Lambda with Filter:
```python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
```
This example uses lambda with the `filter` function to get a list of even numbers from the `numbers` list.
4. Lambda in Sorting:
```python
students = [
{"name": "Alice", "score": 80},
{"name": "Bob", "score": 95},
{"name": "Charlie", "score": 75}
]
students.sort(key=lambda x: x['score'])
print(students)
```
Lambda functions are commonly used in sorting, here sorting a list of dictionaries based on the 'score' key.
5. Lambda in Key Argument:
```python
pairs = [(1, 'one'), (4, 'four'), (3, 'three'), (2, 'two')]
pairs.sort(key=lambda pair: pair[0])
print(pairs)
```
The lambda function here is used as the key argument for sorting a list of tuples based on the first element of each tuple.
Lambda functions are particularly handy for short-lived operations, and they can be a concise way to express functionality in a single line. However, for more complex logic, defining a regular function is often more readable.
0 Comments