What they are

Lambda functions are small, anonymous (unnamed) functions that can be defined in a single line. They're useful for simple operations that don't need a full function definition.

Basic syntax

The pattern is: lambda arguments: expression

# Regular function:
def add(x, y):
    return x + y

# Lambda equivalent:
add = lambda x, y: x + y

# Both work the same:
print(add(3, 5))  # 8

Common use: with map()

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

# Square each number:
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

Common use: with filter()

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

# Get only even numbers:
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6]

Common use: with sorted()

people = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]

# Sort by age (second element):
sorted_by_age = sorted(people, key=lambda x: x[1])
print(sorted_by_age)  # [('Bob', 25), ('Alice', 30), ('Charlie', 35)]

When to use lambdas

  • Simple one-line operations
  • As arguments to functions like map(), filter(), sorted()
  • When the function is only used once
  • Avoid for: complex logic (use regular functions instead)