W3docs

Python Lambda

Learn Python lambda functions: syntax, how to use them with map, filter, and sorted, when to prefer them over def, and their key limitations.

What Is a Lambda Function?

A lambda function is a small, anonymous function defined with the lambda keyword instead of def. Anonymous means it has no name attached to it — though you can assign one to a variable if you need to reuse it. Lambda functions are a concise way to write simple, single-expression functions inline, without the overhead of a full function definition.

Lambda functions are especially useful as short-lived callbacks passed to higher-order functions like map(), filter(), and sorted().

Syntax

lambda arguments: expression
  • arguments — zero or more comma-separated parameters (same as a def function's parameter list, including defaults).
  • expression — a single expression whose value is automatically returned. Statements (like if/else blocks, for loops, or return) are not allowed inside a lambda body.

A valid side-by-side comparison:

def square(x):
    return x ** 2

square_lambda = lambda x: x ** 2

print(square(5))        # Output: 25
print(square_lambda(5)) # Output: 25

Basic Examples

# No arguments
greet = lambda: "Hello, World!"
print(greet())  # Output: Hello, World!

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

# Two arguments
add = lambda x, y: x + y
print(add(10, 20))  # Output: 30

# Default argument value
greet_name = lambda name="World": "Hello, " + name + "!"
print(greet_name())          # Output: Hello, World!
print(greet_name("Alice"))   # Output: Hello, Alice!

Conditional Logic in a Lambda

Because lambdas must be a single expression, you cannot use an if/else statement. You can, however, use a ternary (conditional) expression:

classify = lambda n: "positive" if n > 0 else ("zero" if n == 0 else "negative")

print(classify(5))   # Output: positive
print(classify(0))   # Output: zero
print(classify(-3))  # Output: negative

Deeply nested ternary expressions hurt readability quickly — switch to a regular def function once the logic grows.

Using Lambda with map()

map(function, iterable) applies a function to every element of an iterable and returns a map object. Lambda is a natural fit for the function argument.

nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)  # Output: [2, 4, 6, 8, 10]

The equivalent list comprehension is often preferred for readability:

doubled = [x * 2 for x in nums]  # same result

See List Comprehension for more on that approach.

Using Lambda with filter()

filter(function, iterable) keeps only the elements for which the function returns True.

nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)  # Output: [2, 4]

Using Lambda with sorted()

The key parameter of sorted() (and list.sort()) accepts a callable that returns the comparison value for each element. Lambda makes one-off sort keys concise.

# Sort strings by length
words = ["banana", "apple", "cherry", "date"]
by_length = sorted(words, key=lambda s: len(s))
print(by_length)  # Output: ['date', 'apple', 'banana', 'cherry']

# Sort a list of tuples by the second element
pairs = [(1, "b"), (2, "a"), (3, "c")]
by_second = sorted(pairs, key=lambda p: p[1])
print(by_second)  # Output: [(2, 'a'), (1, 'b'), (3, 'c')]

For more on sorting lists, see Sort Lists.

Immediately Invoked Lambda

A lambda can be called the moment it is defined by wrapping it in parentheses and appending the arguments:

result = (lambda x, y: x + y)(3, 7)
print(result)  # Output: 10

This pattern is uncommon in production code, but occasionally useful in one-off scripts or quick tests.

Lambda Stored in a Data Structure

Because a lambda is a first-class object in Python, you can store lambdas in lists or dictionaries to build simple dispatch tables:

ops = {
    "add": lambda x, y: x + y,
    "sub": lambda x, y: x - y,
    "mul": lambda x, y: x * y,
}

print(ops["add"](3, 4))   # Output: 7
print(ops["sub"](10, 3))  # Output: 7
print(ops["mul"](2, 6))   # Output: 12

Lambda vs. def — When to Use Which

SituationPrefer
Short, single-expression callback passed inlinelambda
Function needs more than one expression or statementdef
Function will be called from many places by namedef
You need a docstring or type annotationsdef
Passed as key= to sorted() / min() / max()lambda (common idiom)

The PEP 8 style guide recommends not assigning a lambda to a variable name when a def would be clearer. For example, prefer def add(x, y): return x + y over add = lambda x, y: x + y when the function lives at module scope.

Key Limitations

  • Single expression only. No assignments, loops, or multi-line logic.
  • No statements. print() is a function call (valid), but assert, raise, or return are statements and cannot appear in a lambda body.
  • No annotations. Type hints (x: int) are not allowed in lambda parameter lists.
  • Harder to debug. Stack traces show <lambda> instead of a meaningful function name.
  • Cannot be pickled. Standard pickle cannot serialize lambda objects — relevant when using multiprocessing.

Relationship to Closures and Decorators

Like a regular function defined with def, a lambda closes over variables in its enclosing scope:

def make_multiplier(n):
    return lambda x: x * n   # 'n' is captured from the enclosing scope

double = make_multiplier(2)
triple = make_multiplier(3)

print(double(5))  # Output: 10
print(triple(5))  # Output: 15

For a deeper look at how closures work in Python, see Python Closures. Lambda functions also appear frequently inside Python Decorators as lightweight wrappers. For a complete look at function definitions, see Python Functions.

Practice

Practice
What is the function of lambda in Python programming?
What is the function of lambda in Python programming?
Was this page helpful?