What are lambda functions in Python?

A lambda is an anonymous one-expression function defined inline. It is useful for short callbacks passed to functions like map(), filter(), and sorted().

Python

Overview

A `lambda` is a way to define a small, anonymous function in a single expression. The syntax is `lambda arguments: expression`. The expression is automatically returned. Lambdas are limited to one expression - use a regular `def` function for anything more complex.

Key Points

  • •Syntax: `lambda x: x * 2` is equivalent to `def f(x): return x * 2`.
  • •Can take multiple arguments: `lambda x, y: x + y`.
  • •Can have default values: `lambda x, n=2: x ** n`.
  • •Commonly used with `sorted()`, `map()`, `filter()`, and `key=` parameters.
  • •Cannot contain statements (no `if`/`for` bodies, no assignment) - only expressions.

Examples

Basic lambda vs equivalent def

python
# Lambda
double = lambda x: x * 2

# Equivalent def
def double(x):
    return x * 2

double(5)  # 10

sorted() with a key lambda

python
users = [
    {'name': 'Charlie', 'age': 35},
    {'name': 'Alice',   'age': 28},
    {'name': 'Bob',     'age': 31},
]

# Sort by age
by_age  = sorted(users, key=lambda u: u['age'])

# Sort by name descending
by_name = sorted(users, key=lambda u: u['name'], reverse=True)

# Sort by multiple fields (age, then name)
by_both = sorted(users, key=lambda u: (u['age'], u['name']))

map() and filter() with lambda

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

# map: transform each element
doubled = list(map(lambda n: n * 2, numbers))  # [2, 4, 6, 8, 10]

# filter: keep elements that pass the test
evens = list(filter(lambda n: n % 2 == 0, numbers))  # [2, 4]

# In modern Python, list comprehensions are usually clearer:
doubled = [n * 2 for n in numbers]
evens   = [n for n in numbers if n % 2 == 0]

Lambda with conditional expression

python
classify = lambda n: 'even' if n % 2 == 0 else 'odd'
classify(4)  # 'even'
classify(7)  # 'odd'

Pro Tip

PEP 8 recommends against assigning a lambda to a variable (`double = lambda x: x * 2`) - just use `def double(x): return x * 2`. Save lambdas for inline use as callbacks and `key=` functions. If a lambda becomes complex, it's a sign to use a named function.