Lambda Functions

Anonymous functions for quick operations

#lambda #functions #anonymous #functional-programming

Lambda Functions

Create small, anonymous functions inline without using def.

Basic Syntax

# Regular function
def square(x):
    return x ** 2

# Lambda equivalent
square = lambda x: x ** 2
print(square(5))  # 25

# With multiple arguments
add = lambda x, y: x + y
print(add(3, 4))  # 7

Common Use Cases

# Sorting with lambda
users = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35}
]
sorted_users = sorted(users, key=lambda u: u['age'])

# Map and filter
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))  # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, numbers))  # [2, 4]

# Reduce
from functools import reduce
total = reduce(lambda acc, x: acc + x, numbers)  # 15

Discover another handy tool from EditPDF.pro