# Topic 2: Lambda Functions

### 1. Introduction

Lambda functions, often referred to as “anonymous functions,” are small, unnamed functions defined using the `lambda` keyword. They can have any number of arguments, but only one expression.

#### 2. Basic Syntax

The general syntax of a lambda function is:

python
```lambda arguments: expression ```

The expression is returned upon calling the lambda function.

#### 3. Basic Example

A simple lambda function that adds two numbers:

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

Notice how the function is defined in a single line and doesn’t have a name.

#### 4. Why Use Lambda Functions?

• Simplicity: They can make code concise, especially when the function logic is simple.
• Temporary Usage: Handy when you need a function for a short period and don’t want to formally define it using `def`.
• Functional Tools: They’re often used in conjunction with functions like `map()`, `filter()`, and `sorted()`.

#### 5. Lambda with `map()`

`map()` applies a function to all items in the input list. Using lambda with `map()`:

python
```numbers = [1, 2, 3, 4] squared = list(map(lambda x: x**2, numbers)) print(squared) # Output: [1, 4, 9, 16] ```

#### 6. Lambda with `filter()`

`filter()` creates a list of elements for which a function returns `True`. Using lambda with `filter()`:

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

#### 7. Lambda with `sorted()`

Lambda functions can help in sorting lists based on custom criteria:

python
```pairs = [(1, 2), (2, 1), (4, 3), (3, 4)] sorted_pairs = sorted(pairs, key=lambda p: p[1]) print(sorted_pairs) # Output: [(2, 1), (1, 2), (4, 3), (3, 4)] ```

Here, the list of tuples is sorted based on the second item in each tuple.

#### 8. Limitations of Lambda Functions

• Single Expression: They can only handle a single expression and cannot contain multiple statements.
• Readability: Can reduce readability when overused or when the logic becomes complex.
• Debugging: Debugging can be a tad difficult since lambda functions are unnamed.

#### 9. When to Use

While lambda functions are powerful, they aren’t always the best choice:

• Short, Simple Operations: They are best suited for short, simple operations that can be expressed in a single expression.
• Temporary Needs: When you need a quick, throw-away function and don’t want to define a full function using `def`.

However, if the functionality gets complex, it’s usually more readable and manageable to define a regular function using the `def` keyword.

#### 10. Conclusion

Lambda functions are a distinctive feature of Python, allowing for the creation of quick, unnamed functions for lightweight tasks. While they are a neat tool to have in your Python toolkit, it’s essential to understand when to use them and when to opt for the more traditional function definition for clarity and maintainability.