Lambda expressions¶
In this tutorial, you will learn how to write concise, anonymous functions using the lambda keyword. Lambda expressions are a powerful tool for short, throwaway operations — especially when combined with built-in functions such as sorted(), map(), and filter().
Time commitment: 15–20 minutes
Prerequisites:
- Python 3.12 or later installed on your machine
- Completion of Tutorial 01 — Defining functions
Learning objectives¶
By the end of this tutorial, you will be able to:
- Understand what lambda expressions are and when to use them
- Write lambda expressions with one or more parameters
- Use lambda expressions with built-in functions like
sorted(),map(), andfilter() - Recognise when a named function is preferable to a lambda
What is a lambda expression?¶
A lambda expression is a small, anonymous function defined with the lambda keyword. Unlike functions created with def, a lambda has no name and consists of a single expression.
The general syntax is:
lambda parameters: expression
The expression is evaluated and returned automatically — you do not use the return keyword. Lambda expressions are most useful when you need a short function for a brief moment and do not want to define a full named function.
Your first lambda¶
Let us start with a simple example. Here is a named function that doubles a number:
def double(x):
return x * 2
print(double(5))
print(double(12))
You can write the same logic as a lambda expression and call it immediately:
print((lambda x: x * 2)(5))
print((lambda x: x * 2)(12))
Both approaches produce the same result. The lambda version is more compact, but calling a lambda directly like this is uncommon — you will see more practical uses shortly.
Lambda with multiple parameters¶
Lambda expressions can accept more than one parameter, just like regular functions. Separate the parameters with commas:
add = lambda a, b: a + b
print(add(3, 7))
print(add(100, 250))
You can also write a lambda with no parameters at all:
greet = lambda: "Hello, World!"
print(greet())
Assigning lambdas to variables¶
In the examples above, we assigned lambda expressions to variables (add, greet). While this works, PEP 8 — the Python style guide — recommends against it. If you need to give a function a name, use def instead.
The reason is simple: a def statement gives the function a proper name that appears in error messages and tracebacks, making debugging easier. A lambda assigned to a variable always shows up as <lambda> in tracebacks.
Compare the following two approaches:
# Discouraged by PEP 8
multiply = lambda x, y: x * y
print(multiply.__name__)
# Preferred
def multiply_numbers(x, y):
return x * y
print(multiply_numbers.__name__)
Notice that the lambda shows <lambda> as its name, while the def function shows multiply_numbers. For the rest of this tutorial, we will use lambdas in the way they were designed — as anonymous, inline functions.
Using lambdas with sorted()¶
One of the most common uses of lambda expressions is as a key function for sorting. The sorted() function accepts a key parameter — a function that extracts a comparison value from each element.
Sort a list of tuples by the second element¶
Suppose you have a list of tuples representing students and their marks:
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78), ("Diana", 95)]
sorted_by_mark = sorted(students, key=lambda student: student[1])
print(sorted_by_mark)
The lambda lambda student: student[1] tells sorted() to use the second element of each tuple (the mark) as the sorting key. The students are now ordered from the lowest mark to the highest.
Sort strings by length¶
You can also sort strings by their length rather than alphabetically:
words = ["banana", "kiwi", "strawberry", "fig", "apple"]
sorted_by_length = sorted(words, key=lambda word: len(word))
print(sorted_by_length)
The words are now arranged from shortest to longest. Without the key parameter, sorted() would sort them alphabetically.
Using lambdas with map()¶
The map() function applies a function to every item in an iterable and returns a map object (which you can convert to a list). Lambda expressions work nicely here when the transformation is simple.
Let us square every number in a list:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda n: n ** 2, numbers))
print(squared)
The lambda lambda n: n ** 2 takes each number and returns its square. The map() function applies this to every element, producing [1, 4, 9, 16, 25].
Here is another example — converting a list of temperatures from Celsius to Fahrenheit:
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: round(c * 9 / 5 + 32, 1), celsius))
print(fahrenheit)
Using lambdas with filter()¶
The filter() function tests each item in an iterable against a function and keeps only those for which the function returns True.
Let us filter a list to keep only even numbers:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda n: n % 2 == 0, numbers))
print(even_numbers)
The lambda lambda n: n % 2 == 0 returns True for even numbers and False for odd numbers. Only the even numbers make it through the filter.
Here is another example — filtering a list of words to keep only those longer than four characters:
words = ["cat", "elephant", "dog", "hippopotamus", "ant", "giraffe"]
long_words = list(filter(lambda w: len(w) > 4, words))
print(long_words)
When not to use lambdas¶
Lambda expressions are wonderful for short, simple operations, but they have limitations. You should use a named def function instead when:
- The logic is complex. A lambda must be a single expression. If you need multiple statements, conditional blocks, or loops, use
def. - You need to reuse the function. If you call the same logic in several places, a named function is clearer and avoids duplication.
- Readability suffers. If a lambda is difficult to understand at a glance, a named function with a descriptive name will make your code easier to read.
- You need a docstring. Lambda expressions cannot have docstrings, so they are not suitable when documentation is important.
For example, this lambda is too complex and should be a named function:
# Hard to read as a lambda
categorise = lambda x: "high" if x > 80 else ("medium" if x > 50 else "low")
print(categorise(90))
print(categorise(65))
print(categorise(30))
# Much clearer as a named function
def categorise_score(score):
if score > 80:
return "high"
elif score > 50:
return "medium"
else:
return "low"
print(categorise_score(90))
print(categorise_score(65))
print(categorise_score(30))
Both versions produce the same result, but the named function is significantly easier to read and maintain.
Exercise¶
Put your new skills into practice with the following two tasks.
Task 1: Sort a list of dictionaries¶
You have the following list of books. Write a lambda expression to sort them by price, from lowest to highest.
books = [
{"title": "Python Basics", "price": 29.99},
{"title": "Advanced Algorithms", "price": 49.99},
{"title": "Data Science Handbook", "price": 39.99},
{"title": "Web Development Guide", "price": 24.99},
]
Task 2: Filter with a threshold¶
Using the same list of books, use filter() with a lambda to keep only books that cost more than £30.
books = [
{"title": "Python Basics", "price": 29.99},
{"title": "Advanced Algorithms", "price": 49.99},
{"title": "Data Science Handbook", "price": 39.99},
{"title": "Web Development Guide", "price": 24.99},
]
# Task 1: Sort books by price (lowest to highest)
# sorted_books = ...
# Task 2: Keep only books that cost more than £30
# expensive_books = ...
Solution¶
books = [
{"title": "Python Basics", "price": 29.99},
{"title": "Advanced Algorithms", "price": 49.99},
{"title": "Data Science Handbook", "price": 39.99},
{"title": "Web Development Guide", "price": 24.99},
]
# Task 1: Sort books by price
sorted_books = sorted(books, key=lambda book: book["price"])
for book in sorted_books:
print(f"{book['title']}: £{book['price']}")
# Task 2: Filter books costing more than £30
expensive_books = list(filter(lambda book: book["price"] > 30, books))
for book in expensive_books:
print(f"{book['title']}: £{book['price']}")
Summary¶
In this tutorial, you learned how to:
- Write lambda expressions as concise, anonymous functions using the
lambdakeyword - Create lambdas with zero, one, or multiple parameters
- Use lambda expressions as key functions with
sorted()to customise sort order - Apply
map()with a lambda to transform every element in a list - Use
filter()with a lambda to select elements that meet a condition - Recognise when a named
deffunction is a better choice than a lambda
What is next¶
In the next tutorial, Type hints, you will learn how to add type annotations to your function signatures. Type hints make your code clearer, help your editor provide better suggestions, and allow tools like mypy to catch type-related errors before your code runs.