Codectionary / Developer documentation / Python

lambda

A lambda is a small, anonymous, single-expression function, created without the def keyword or a name. Lambdas are restricted to a single expression whose result is automatically returned - they can't contain multiple statements or assignments. They're most useful as short, throwaway functions passed as arguments to other functions like sorted(), map(), and filter().

Syntax

lambda arguments: expression

Examples

Basic Lambda

Comparing a lambda to an equivalent regular function.

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

# Equivalent regular function
def square_normal(x):
    return x ** 2

Lambda with sorted()

Using a lambda as the 'key' function to control sort order.

students = [
    {"name": "John", "grade": 85},
    {"name": "Zain", "grade": 92},
    {"name": "Jamal", "grade": 78}
]

by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
    print(s["name"], s["grade"])

Lambda with map() and filter()

Using lambdas as quick, inline transformation and filter functions.

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

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

evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)  # [2, 4]

Lambda with Multiple Arguments

Lambdas can accept multiple parameters, just like regular functions.

add = lambda a, b: a + b
print(add(3, 4))  # 7

# Lambda with a default argument
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("John"))
print(greet("John", "Hey"))

Best practices

  • Use lambdas for short, throwaway functions passed as arguments (sort keys, map/filter callbacks) - not for complex logic
  • Prefer a regular def function once a lambda's expression starts feeling hard to read on one line
  • Avoid assigning a lambda to a variable name just to give it a name - use def instead, since it's more readable and gives better error tracebacks
  • Remember a lambda can only contain a single expression, not statements like assignments, loops, or multiple lines

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading