2024年11月21日木曜日

Lambda Functions in Python

Lambda functions, also known as anonymous functions, are small, unnamed functions that can be defined in a single line of code. They're often used for simple tasks that don't require a full function definition.

Basic Syntax:

Python
lambda arguments: expression

Breakdown:

  • lambda: Keyword to define a lambda function.
  • arguments: One or more arguments, separated by commas.
  • expression: The expression to be evaluated and returned.

Example:

Python
square = lambda x: x * x
print(square(5))  # Output: 25

Key Points:

  • Concise: Lambda functions provide a concise way to define simple functions.
  • Single Expression: They can only contain a single expression.
  • Useful in Higher-Order Functions: Often used as arguments to higher-order functions like map, filter, and reduce.

Common Use Cases:

  1. Sorting:

    Python
    numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    sorted_numbers = sorted(numbers, key=lambda x: x % 2)
    print(sorted_numbers)  # Output: [2, 4, 6, 1, 1, 3, 3, 5, 5, 5, 9]
    
  2. Filtering:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # Output: [2, 4, 6, 8, 10]1


3. **Mapping:**

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

When to Use Lambda Functions:

  • Simple Operations: For straightforward operations that can be expressed in a single line.
  • Higher-Order Functions: As arguments to functions like map, filter, and sorted.
  • Quick and Dirty Functions: For one-time use or small, temporary functions.

Remember: While lambda functions are powerful, they can sometimes make code less readable if overused. Use them judiciously and consider defining a regular function for more complex operations or when readability is a priority.

0 件のコメント:

コメントを投稿