How to Use Lambda in Python

What you'll build or solve

You'll write and use lambda functions for quick, single-expression logic.

When this approach works best

A lambda works well when you:

  • Pass a short function to sorted(), like sorting by the second item in a tuple.
  • Transform values in a pipeline, like converting a list of strings to integers.
  • Filter data with a simple rule, like keeping only items longer than 3 characters.

Avoid lambdas when the logic needs multiple steps, branching, or reuse. Use def so you can name the function, add comments, and test it independently.

Prerequisites

  • Python installed
  • You know what a function is

Step-by-step instructions

1) Write a lambda function

A lambda is an anonymous function with this shape:

add = lambda a, b: a + b
print(add(2, 3))

What to look for:

A lambda can only contain one expression. You cannot put statements like try/except or multi-line logic inside it.


2) Use a lambda as a key function for sorting

This is one of the most common uses. The lambda returns the value Python should sort by.

people = [
    {"name": "Naomi", "age": 30},
    {"name": "Ivan", "age": 22},
    {"name": "Lea", "age": 27},
]

sorted_people = sorted(people, key=lambda person: person["age"])
print(sorted_people)

Option A: Sort by two fields

people = [
    {"name": "Naomi", "age": 30},
    {"name": "Ivan", "age": 22},
    {"name": "Lea", "age": 22},
]

sorted_people = sorted(
    people,
    key=lambda person: (person["age"], person["name"])
)
print(sorted_people)

What to look for:

Return a tuple for multi-field sorting. Python compares the first element, then the next if there is a tie.


3) Use a lambda with map() and filter()

Use map() to transform items, and filter() to keep items that match a condition.

numbers = ["1", "2", "3", "10"]

as_ints = list(map(lambda s: int(s), numbers))
print(as_ints)

Option A: Filter items

words = ["hi", "hello", "podgorica", "ok"]

long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words)

What to look for:

map() and filter() return iterators in Python 3. Wrap them in list() if you want to print the results or reuse them.


Examples you can copy

Example 1: Sort a list of tuples by the second value

pairs = [("a", 3), ("b", 1), ("c", 2)]
sorted_pairs = sorted(pairs, key=lambda item: item[1])
print(sorted_pairs)

Example 2: Sort strings case-insensitively

names = ["Mila", "ana", "Ivan"]
sorted_names = sorted(names, key=lambda s: s.casefold())
print(sorted_names)

Example 3: Convert a list of prices like "€10" into integers

prices = ["€10", "€2", "€7"]

numbers = list(map(lambda p: int(p.lstrip("€")), prices))
print(numbers)

Example 4: Filter out empty or whitespace-only strings

items = ["ok", " ", "", "done", "   "]
clean = list(filter(lambda s: s.strip() != "", items))
print(clean)

Example 5: Build a quick lookup mapping from data

users = [
    {"id": "u1", "name": "Naomi"},
    {"id": "u2", "name": "Ivan"},
]

id_to_name = dict(map(lambda u: (u["id"], u["name"]), users))
print(id_to_name)

Common mistakes and how to fix them

Mistake 1: Putting complex logic into a lambda

What you might do

numbers = [1, 2, 3, 4]
result = list(
    map(lambda n: n * 2 if n % 2 == 0 else n * 3 if n > 2 else n, numbers)
)
print(result)

Why it breaks

This works, but it is hard to read and easy to mess up.

Fix

Use a named function:

def transform(n):
    if n % 2 == 0:
        return n * 2
    if n > 2:
        return n * 3
    return n

numbers = [1, 2, 3, 4]
result = list(map(transform, numbers))
print(result)

Mistake 2: Forgetting that map() and filter() return iterators

What you might do

numbers = ["1", "2", "3"]
mapped = map(lambda s: int(s), numbers)
print(mapped)

Why it breaks

Printing shows an iterator object, not the values.

Fix

Convert to a list (or loop over it):

numbers = ["1", "2", "3"]
mapped = list(map(lambda s: int(s), numbers))
print(mapped)

Troubleshooting

If you get a syntax error in a lambda, check that you used only one expression and no statements.

If sorting results look wrong, print the key you return from the lambda for a couple of items to confirm it matches what you want.

If map() or filter() seems empty on the second use, you already consumed the iterator. Convert to a list if you need to reuse it.

If a lambda feels unreadable, switch to def and give it a clear name.

If your lambda accesses a missing dictionary key, use get() or validate the data before sorting or mapping.


Quick recap

  • Use lambda args: expression for short, one-off functions.
  • Lambdas work best as key= functions for sorted() and quick transforms with map() or filter().
  • Lambdas can only contain one expression.
  • Convert map() and filter() to a list when you need to print or reuse the results.
  • Use def when the logic is more than a simple expression.