</>
Skip to content
Python lessons (22/45)

Python — Lambda

What is a lambda?

A lambda is a small, anonymous function defined in one line:

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

Syntax: lambda parameters: expression

The expression is evaluated and returned automatically — no return needed.

Lambda vs def

# Lambda
square = lambda x: x ** 2

# Equivalent def
def square(x):
    return x ** 2

Both do the same thing. Lambdas are limited to a single expression — no assignments, no multiple statements, no docstrings.

When to use lambdas

Lambdas are most useful where a small function is needed temporarily — as an argument to another function:

# Sorting with a custom key
students = [("Alice", 90), ("Bob", 75), ("Charlie", 85)]
students.sort(key=lambda s: s[1])  # sort by score
print(students)  # [('Bob', 75), ('Charlie', 85), ('Alice', 90)]

# Filtering
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]

# Mapping
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Lambda with sorted()

The most common use case — custom sorting:

# Sort by last name
people = ["Alice Smith", "Bob Jones", "Charlie Brown"]
people.sort(key=lambda name: name.split()[-1])
print(people)  # ['Charlie Brown', 'Alice Smith', 'Bob Jones']

# Sort dictionaries by value
inventory = {"apples": 5, "bananas": 2, "cherries": 8}
sorted_items = sorted(inventory.items(), key=lambda item: item[1], reverse=True)
print(sorted_items)  # [('cherries', 8), ('apples', 5), ('bananas', 2)]

# Sort by multiple keys
students = [
    {"name": "Alice", "grade": "A", "age": 20},
    {"name": "Bob", "grade": "B", "age": 22},
    {"name": "Charlie", "grade": "A", "age": 19}
]
students.sort(key=lambda s: (s["grade"], -s["age"]))

Lambda with filter()

filter() keeps elements where the function returns True:

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

# Keep odd numbers
odds = list(filter(lambda x: x % 2 != 0, numbers))
print(odds)  # [1, 3, 5, 7, 9]

# Keep positive numbers
mixed = [-3, 1, -4, 1, 5, -9, 2, 6]
positives = list(filter(lambda x: x > 0, mixed))
print(positives)  # [1, 1, 5, 2, 6]

# Keep strings longer than 3 characters
words = ["hi", "hello", "hey", "howdy", "yo"]
long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words)  # ['hello', 'howdy']

Lambda with map()

map() applies a function to every element:

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

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

# Convert to strings
labels = list(map(lambda x: f"Item {x}", numbers))
print(labels)  # ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']

# Combine two lists
names = ["Alice", "Bob"]
scores = [90, 75]
results = list(map(lambda n, s: f"{n}: {s}", names, scores))
print(results)  # ['Alice: 90', 'Bob: 75']

List comprehensions vs lambdas

For most cases, list comprehensions are more Pythonic:

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

# Lambda + map
squares_map = list(map(lambda x: x ** 2, numbers))

# List comprehension (preferred)
squares_comp = [x ** 2 for x in numbers]

# Lambda + filter
evens_filter = list(filter(lambda x: x % 2 == 0, numbers))

# List comprehension (preferred)
evens_comp = [x for x in numbers if x % 2 == 0]

List comprehensions are generally faster and more readable. Use lambdas when you need a function as an argument (like sorted(key=...)).

Closures with lambdas

Lambdas can capture variables from their enclosing scope:

def make_adder(n):
    return lambda x: x + n

add5 = make_adder(5)
add10 = make_adder(10)

print(add5(3))    # 8
print(add10(3))   # 13

This creates a closure — the lambda remembers n even after make_adder returns.

Multiple parameters

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

full_name = lambda first, last: f"{first} {last}"
print(full_name("Ada", "Lovelace"))  # Ada Lovelace

Immediate invocation

Call a lambda immediately:

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

This is useful for one-off calculations but generally discouraged — named functions are clearer.

Practical examples

Transforming data

transactions = [
    {"item": "apple", "price": 1.50, "quantity": 3},
    {"item": "banana", "price": 0.75, "quantity": 6},
    {"item": "cherry", "price": 3.00, "quantity": 2}
]

# Calculate total for each transaction
totals = list(map(
    lambda t: {"item": t["item"], "total": t["price"] * t["quantity"]},
    transactions
))
print(totals)
# [{'item': 'apple', 'total': 4.5}, {'item': 'banana', 'total': 4.5}, ...]

Conditional transformation

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

# Negate even numbers, keep odd
result = list(map(lambda x: -x if x % 2 == 0 else x, numbers))
print(result)  # [1, -2, 3, -4, 5]

Reducing with functools

from functools import reduce

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

print(f"Sum: {total}")      # 15
print(f"Product: {product}")  # 120

When NOT to use lambdas

# Bad — complex logic in a lambda
process = lambda x: x ** 2 if x > 0 else 0 if x == 0 else -x

# Good — use a def for complex logic
def process(x):
    if x > 0:
        return x ** 2
    elif x == 0:
        return 0
    else:
        return -x

Use lambdas for simple, one-line transformations. Use def for anything that needs multiple statements, docstrings, or error handling.

Mini Practice

  1. Use a lambda with sorted() to sort a list of words by length
  2. Use filter() with a lambda to keep only palindromes from a list of strings
  3. Use map() with a lambda to convert a list of temperatures from Celsius to Fahrenheit
  4. Create a lambda closure that generates a "greeting maker" — make_greeting("Hey") returns a function
  5. Use reduce() with a lambda to find the largest number in a list without using max()

Next: classes and objects →

Related Topics

Frequently Asked Questions about Lambda

What is Lambda in Python?

Lambda is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Lambda?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lambda.

Why is Lambda important in Python?

Lambda is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.