Python Lambda Anonymous Function

A lambda function is an anonymous function defined with the lambda keyword. It can take any number of arguments but can only contain a single expression. The result of that expression is returned automatically.

The syntax is lambda arguments: expression. There is no return statement because the expression is evaluated and its result is returned implicitly. This makes lambdas useful for short throwaway functions where defining a full def would be overkill.

Lambda Syntax Explained

Compare a regular function with its lambda equivalent. Both do the same thing.

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

# Lambda equivalent
square = lambda x: x ** 2

print(square(5))  # 25

Lambda arguments work exactly like def arguments. You can have positional args, keyword args, defaults, and *args.

# No arguments
noop = lambda: 42
print(noop())  # 42

# Multiple arguments
add = lambda x, y: x + y
print(add(3, 4))  # 7

# With default argument
power = lambda x, exp=2: x ** exp
print(power(3))   # 9
print(power(3, 3)) # 27

Using Lambdas with Built-in Functions

Lambda functions shine when combined with Python built-ins like map, filter, and sorted. These functions accept a callable as their first argument, and lambdas provide that callable without the overhead of a named function.

map() with Lambda

map(function, iterable) applies the function to every item in the iterable and returns an iterator.

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

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

names = ['alice', 'bob', 'charlie']
upper = list(map(lambda s: s.upper(), names))
print(upper)  # ['ALICE', 'BOB', 'CHARLIE']

filter() with Lambda

filter(function, iterable) keeps only the items where the function returns True.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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

words = ['hi', 'hello', 'hey', 'yo', 'greetings']
long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words)  # ['hello', 'greetings']

sorted() with Lambda

The key argument of sorted accepts a function. Lambda is perfect here because you rarely need a named function for sorting logic.

people = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35}
]

# Sort by age
by_age = sorted(people, key=lambda p: p['age'])
print([p['name'] for p in by_age])  # ['Bob', 'Alice', 'Charlie']

# Sort by name length
by_name_len = sorted(people, key=lambda p: len(p['name']))
print([p['name'] for p in by_name_len])  # ['Bob', 'Alice', 'Charlie']

max() and min() with Lambda

orders = [
    {'product': 'Laptop', 'price': 999},
    {'product': 'Mouse', 'price': 29},
    {'product': 'Keyboard', 'price': 79}
]

most_expensive = max(orders, key=lambda o: o['price'])
cheapest = min(orders, key=lambda o: o['price'])
print(most_expensive['product'])  # Laptop
print(cheapest['product'])        # Mouse

Lambda vs list comprehension

Everything you can do with map and filter combined with lambda, you can do with a list comprehension. List comprehensions are generally preferred in Python for readability.

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

# Lambda + map - don't do this
squares = [x ** 2 for x in numbers]  # List comprehension is cleaner

# Lambda + filter - don't do this
evens = [x for x in numbers if x % 2 == 0]  # List comprehension is cleaner

# Where lambda IS appropriate with sorted, max, min
max_val = max(numbers, key=lambda x: -x)  # Finds maximum

The exception is sorted, max, and min with a key function. You cannot replace these with list comprehensions, so lambda is genuinely useful there.

Lambda and Closures

Lambda captures variables from its enclosing scope at definition time, not at call time. This is called closure.

def make_multiplier(factor):
    return lambda x: x * factor

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

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

# The lambda captured the `factor` argument at definition time
# Each lambda has its own closure value

Common Mistakes with Lambda

Mutable default arguments

Never use a lambda to create a function that modifies a default mutable argument. This is a common trap that leads to subtle bugs.

# WRONG - this is a classic Python gotcha
bad_func = lambda lst=[]: lst.append('x')

# Default mutable arguments are shared across calls
# Use a proper function with default None instead
def good_func(lst=None):
    if lst is None:
        lst = []
    lst.append('x')
    return lst

Multi-expression lambdas

If your lambda is getting complex, it is a sign you should use a regular def function. Lambdas are meant for single expressions.

<pre class="wp-block-syntaxhighlighter-code"># WRONG - lambda too complex
complex_lambda = lambda x: (x > 0 and 'positive' or x < 0 and 'negative' or 'zero')
# CORRECT - use def
def classify(x):
    if x > 0: return 'positive'
    elif x < 0: return 'negative'
    return 'zero'</pre>

When to Use Lambda vs def

Use lambda when you need a short, throwaway function for sorted, max, min, map, or filter. Use def when the function needs multiple statements, documentation, or is used in multiple places.

  • Use lambda with sorted(key=...) – genuinely the best tool
  • Use lambda with max/min(key=...) – genuinely the best tool
  • Use lambda with map/filter – list comprehensions are usually better
  • Use def for anything over 2-3 lines of code
  • Use def if the function is referenced in multiple places

Practical Example: Sorting a Table

Lambdas are most practical when sorting data structures. Here is a realistic example sorting a list of records by multiple fields.

employees = [
    {'name': 'Alice', 'dept': 'Engineering', 'salary': 90000},
    {'name': 'Bob', 'dept': 'Sales', 'salary': 75000},
    {'name': 'Charlie', 'dept': 'Engineering', 'salary': 95000},
    {'name': 'Diana', 'dept': 'Sales', 'salary': 80000}
]

# Sort by dept, then by salary descending within each dept
sorted_employees = sorted(
    employees,
    key=lambda e: (e['dept'], -e['salary'])
)

for emp in sorted_employees:
    print(f"{emp['dept']:12} {emp['salary']:8} {emp['name']}")
# Engineering   95000 Charlie
# Engineering   90000 Alice
# Sales         80000 Diana
# Sales         75000 Bob

FAQ

  • Can a lambda function have multiple statements? No. A lambda can only contain a single expression. Use a regular def function for multiple statements.
  • Can lambdas access variables outside themselves? Yes. Lambdas support closures and can access variables from the enclosing scope.
  • What is the difference between def and lambda? Lambda defines an anonymous expression and returns its result automatically. def defines a named function that can contain multiple statements.
  • When should I prefer list comprehension over map/filter with lambda? Almost always. List comprehensions are more readable in Python. The exception is sorted(key=...) and max/min(key=...).
  • Can I use lambda without any arguments? Yes. lambda: 42 creates a function that takes no arguments and returns 42.
Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 241