# 62. Lambda Functions

**Lambda Functions in Python**

Lambda functions in Python are anonymous (unnamed) functions that are defined using the `lambda` keyword. They are usually one-liner functions that can accept any number of arguments but only have one expression.

The syntax for a lambda function is:

```python
lambda arguments: expression
```

Where:

* `arguments` are the input parameters (can be multiple, separated by commas).
* `expression` is a single expression whose result is returned.

Lambda functions are often used in places where you need a small function for a short period and don't want to formally define a function using `def`.

**1. Basic Example**

A simple lambda function that adds two numbers:

```python
add = lambda x, y: x + y
print(add(5, 3))  # Output: 8
```

In this example, `lambda x, y: x + y` is equivalent to the following function:

```python
def add(x, y):
    return x + y
```

**2. Lambda with Sorting**

Lambda functions are frequently used with functions like `sorted()`, where you need to specify a custom sorting key.

For example, sorting a list of tuples based on the second element:

```python
data = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
```

**Output:**

```
[(1, 'apple'), (2, 'banana'), (3, 'cherry')]
```

Here, the lambda function `lambda x: x[1]` tells `sorted()` to sort the tuples by the second element (the fruit name).

**3. Using Lambda with `map()`**

`map()` is a function that applies a function to all items in an iterable (like a list) and returns a map object (which is an iterator).

For example, multiplying each number in a list by 2:

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

**4. Using Lambda with `filter()`**

`filter()` is used to filter elements from an iterable based on a condition.

For example, filtering out even numbers from a list:

```python
numbers = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))  # Output: [2, 4, 6]
```

Here, the lambda function `lambda x: x % 2 == 0` returns `True` for even numbers, which are included in the result.

**5. Using Lambda with `reduce()`**

`reduce()` is used to apply a binary function (a function that takes two arguments) cumulatively to the items in an iterable, from left to right, to reduce the iterable to a single value. It is available in the `functools` module.

For example, calculating the product of all numbers in a list:

```python
from functools import reduce

numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, numbers)
print(result)  # Output: 120
```

The lambda function `lambda x, y: x * y` multiplies all the elements together.

**6. Lambda with Default Arguments**

Lambda functions can also have default arguments:

```python
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("Alice"))           # Output: Hello, Alice!
print(greet("Alice", "Hi"))     # Output: Hi, Alice!
```

**7. Lambda Inside Other Functions**

You can also use lambda functions inside other functions or methods. For instance, defining a lambda function inside a higher-order function:

```python
def apply_func(func, x, y):
    return func(x, y)

result = apply_func(lambda x, y: x ** y, 2, 3)
print(result)  # Output: 8
```

**8. Lambda with `max()` and `min()`**

Lambda functions are useful when you want to get the max or min element based on a custom key.

For example, getting the maximum length string from a list:

```python
words = ["apple", "banana", "cherry", "kiwi"]
longest_word = max(words, key=lambda word: len(word))
print(longest_word)  # Output: banana
```

**9. Nested Lambda Functions**

You can nest lambda functions, though it’s generally discouraged for readability purposes.

For example:

```python
multiply = lambda x: (lambda y: x * y)
result = multiply(5)(2)
print(result)  # Output: 10
```

In this example, the outer lambda function returns another lambda function that takes `y` and multiplies it by `x`.

**10. Lambda for Mathematical Operations**

Lambda functions can be used for mathematical operations directly.

```python
square = lambda x: x ** 2
cube = lambda x: x ** 3

print(square(4))  # Output: 16
print(cube(3))    # Output: 27
```

**Summary**

* **Lambda functions** are anonymous, one-line functions created with the `lambda` keyword.
* They're often used in situations where you need a short, simple function for a brief period of time.
* Common uses include filtering, mapping, reducing, sorting, and handling operations like applying custom functions to iterables.

Though lambda functions can make your code concise, they are best used for short, simple operations. For more complex logic, a regular function defined with `def` might be clearer.
