Lambda Functions in Python

 Lambda functions in Python are small, anonymous functions defined with the `lambda` keyword. They can have any number of arguments but only one expression. The expression is evaluated and returned when the lambda function is called. Lambda functions are typically used for short, simple operations that are convenient to define inline.


 Syntax

```python

lambda arguments: expression

```


 Example 1: Basic Lambda Function

```python

# A lambda function that adds 10 to the input

add_ten = lambda x: x + 10

print(add_ten(5))  # Output: 15

```


 Example 2: Lambda with Multiple Arguments

```python

# A lambda function that multiplies two numbers

multiply = lambda x, y: x * y

print(multiply(3, 4))  # Output: 12

```


 Example 3: Using Lambda with `map()`

```python

# Use a lambda function to square each element in a list

numbers = [1, 2, 3, 4]

squared = list(map(lambda x: x**2, numbers))

print(squared)  # Output: [1, 4, 9, 16]

```


 Example 4: Using Lambda with `filter()`

```python

# Use a lambda function to filter even numbers from a list

numbers = [1, 2, 3, 4, 5, 6]

evens = list(filter(lambda x: x % 2 == 0, numbers))

print(evens)  # Output: [2, 4, 6]

```


Example 5: Using Lambda with `sorted()`

```python

# Use a lambda function to sort a list of tuples by the second element

pairs = [(1, 9), (2, 8), (3, 7)]

sorted_pairs = sorted(pairs, key=lambda x: x[1])

print(sorted_pairs)  # Output: [(3, 7), (2, 8), (1, 9)]

```


Key Points

1. **Anonymous**: Lambda functions are anonymous, meaning they don't have a name unless assigned to a variable.

2. **Single Expression**: They can only contain one expression, which is evaluated and returned.

3. **Inline Use**: Often used for short, throwaway functions where defining a full function with `def` would be overkill.

4. **Functional Programming**: Commonly used with functions like `map()`, `filter()`, and `sorted()`.


### Limitations

- Lambda functions are limited to a single expression, so they cannot include complex logic or multiple statements.

- They are less readable for complex operations, so in such cases, a regular function defined with `def` is preferred.


Let me know if you'd like further clarification or examples!

Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Kotlin Strings: Features and Operations Guide

Kotlin Android Program (QCR) Application Codes That Read Text in Photos