Skip to content

Lambda Functions

Anonymous functions with lambda: syntax, use with map/filter/sorted, and when to avoid them.

What you'll learn

  • Write lambda expressions for simple functions
  • Use lambdas with map(), filter(), and sorted()
  • Understand lambda limitations and scope
  • Choose between lambda and def appropriately
  • Apply lambdas as key functions in sorting

Concept

What Is a Lambda?

A lambda is a small anonymous function defined in a single expression. It is useful for short, throwaway functions that you do not need to name:

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

# Equivalent lambda
square = lambda x: x ** 2

print(square(5))  # 25 (works the same)

The syntax is lambda parameters: expression. The expression is evaluated and returned automatically — there is no return keyword. Lambdas can have multiple parameters but only one expression.

Multiple Parameters

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

# Default values work too
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("Ada"))  # Hello, Ada!

Using Lambda with map()

map() applies a function to every item in an iterable:

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

# Equivalent list comprehension (often preferred)
squared = [x ** 2 for x in numbers]

In modern Python, list comprehensions are usually preferred over map() with a lambda — they are more readable and often faster. However, map() can be cleaner when you already have a named function.

Using Lambda with filter()

filter() keeps 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))
# [2, 4, 6, 8, 10]

# Equivalent list comprehension (preferred)
evens = [x for x in numbers if x % 2 == 0]

Again, list comprehensions are generally preferred for readability.

Using Lambda with sorted() — The Best Use Case

The most common and justified use of lambda is as a key function in sorting:

students = [
    {"name": "Ada", "grade": 85},
    {"name": "Bob", "grade": 92},
    {"name": "Cy", "grade": 78},
]

# Sort by grade (descending)
students_sorted = sorted(students, key=lambda s: s["grade"], reverse=True)

# Sort by name length
by_name_length = sorted(students, key=lambda s: len(s["name"]))

# Sort tuples by second element
pairs = [(1, 3), (2, 1), (3, 2)]
sorted_pairs = sorted(pairs, key=lambda p: p[1])

This is where lambdas shine — a short, inline function that extracts the sort key. Using a named def for a one-line key extractor would be unnecessarily verbose.

Using Lambda with reduce()

functools.reduce() applies a function cumulatively to reduce an iterable to a single value:

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda a, b: a * b, numbers)
# 120 (1*2*3*4*5)

# Equivalent without reduce:
product = 1
for n in numbers:
    product *= n

reduce() is less common and can be hard to read — a regular loop is often clearer.

Lambda Limitations

Lambdas are restricted to a single expression — no statements, no assignments, no multi-line logic:

# This is INVALID — lambdas cannot have statements
# lambda x: if x > 0: return x else: return -x

# Use a regular function instead:
def abs_val(x):
    if x > 0:
        return x
    return -x

Lambdas cannot contain:

  • if statements (use ternary x if cond else y instead)
  • for / while loops
  • try / except
  • Variable assignments (no = in the body)
  • Multiple expressions

Late Binding Gotcha

Lambdas capture variables by reference, not by value. This causes a classic bug in loops:

# BUG — all lambdas return 4!
funcs = [lambda: i for i in range(5)]
print([f() for f in funcs])  # [4, 4, 4, 4, 4]

# FIX — use a default argument to capture the current value
funcs = [lambda i=i: i for i in range(5)]
print([f() for f in funcs])  # [0, 1, 2, 3, 4]

The default argument i=i evaluates at definition time, capturing the current value of i.

When to Use Lambda vs def

Use lambda when:

  • The function is a single simple expression
  • It is used inline (as a key, callback, or argument to map/filter)
  • You do not need to reuse it or give it a name

Use def when:

  • The function has multiple statements
  • You need a docstring
  • The function is reused or needs a name for clarity
  • The logic is complex

PEP 8: "Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name." In other words, do not write f = lambda x: x + 1 — write def f(x): return x + 1 instead. Assigning a lambda to a name defeats its purpose.

Example

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

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

# Lambda as a sort key — the best use case
students = [
    {"name": "Ada", "grade": 85},
    {"name": "Bob", "grade": 92},
    {"name": "Cy", "grade": 78},
]

# Sort by grade descending
by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
    print(f"  {s['name']}: {s['grade']}")

# Sort by name length
by_len = sorted(students, key=lambda s: len(s["name"]))
print([s["name"] for s in by_len])

# map() with lambda
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squared: {squared}")

# filter() with lambda
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")

# reduce() with lambda
from functools import reduce
product = reduce(lambda a, b: a * b, numbers)
print(f"Product: {product}")  # 120

# Late binding fix — default argument
funcs = [lambda i=i: i for i in range(5)]
print([f() for f in funcs])  # [0, 1, 2, 3, 4]

# Practical: sort strings case-insensitively
words = ["Banana", "apple", "Cherry", "date"]
sorted_words = sorted(words, key=lambda w: w.lower())
print(sorted_words)  # ['apple', 'Banana', 'Cherry', 'date']
            

Shows basic lambdas, multiple parameters, the key function use case with sorted(), map/filter/reduce, the late-binding gotcha and its fix, and a practical case-insensitive sort.

Try it

  • Text Counter

    Lambdas are useful for transforming counted text statistics.

  • Case Converter

    Lambda key functions can sort by case-converted values.

Common mistakes

The mistake

Assigning a lambda to a variable name: f = lambda x: x + 1

The fix

PEP 8 says: always use a def statement instead of binding a lambda to a name. Write 'def f(x): return x + 1' instead. Lambdas are meant for inline use (as key functions or callbacks), not as named functions.

The mistake

The late binding bug: [lambda: i for i in range(5)] all return 4

The fix

Lambdas capture variables by reference, so all functions see the final loop value. Fix with a default argument: [lambda i=i: i for i in range(5)]. The default is evaluated at definition time, capturing the current value.

Related Cheatsheets

Practice Lambda Functions

4 exercises

Practice Lambda Functions

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors