Python Lambda

A lambda is a small, unnamed function written in a single expression, useful when you need a quick throwaway function.

What a lambda is

A lambda function is an anonymous function defined with the lambda keyword rather than def. It can take any number of arguments but must consist of a single expression, whose value is returned automatically. Because it fits on one line, a lambda is handy for short operations that do not deserve a full named function.

A lambda compared with a regular function

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

# Equivalent lambda
double = lambda x: x * 2

print(double(6))  # 12

Lambdas with several arguments

A lambda can accept more than one argument by separating them with commas before the colon. There is no return keyword inside a lambda; the result of the single expression is what gets returned.

Multiple arguments in one expression

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

full = lambda first, last: first + " " + last
print(full("Ada", "Lovelace"))  # Ada Lovelace

Where lambdas shine

Lambdas are most useful when passed to functions that expect another function as an argument, such as sorted, map, and filter. Providing a short lambda inline is often clearer than defining a separate named function that is used only once.

Sorting and filtering with a lambda

people = [("Ana", 32), ("Ben", 25), ("Cara", 41)]

# Sort by the age, which is the second item
by_age = sorted(people, key=lambda person: person[1])
print(by_age)
# [('Ben', 25), ('Ana', 32), ('Cara', 41)]

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)  # [2, 4, 6]
Note: If a lambda grows long or hard to read, switch to a normal def function. Lambdas are meant for short, simple expressions.

Lambda versus def at a glance

  • A lambda has no name unless you assign it to a variable.
  • A lambda holds a single expression, while a def function can contain many statements.
  • A lambda returns its expression automatically, so it never uses the return keyword.
  • Use a lambda for short inline logic and a def function for anything longer or reused.