Lesson 7 of 16 · Functions in Depth
Lambda Functions
Learn Python lambda functions: write small one-line functions, use them as sort keys and know when a normal def function is the better choice.
- 7 min read
- Intermediate
- Reviewed
- What a lambda function is and how to write one
- How lambdas compare with functions made with def
- How to use a lambda as a sort key
- When not to use a lambda
Functions are values too
Before lambdas, one important idea. A function is a value, just like a number or a list. You can store it in a variable and pass it to another function.
def shout(text):
return text.upper() + "!"
say = shout
print(say("hello"))
def apply_twice(function, value):
return function(function(value))
print(apply_twice(shout, "hi"))Notice say = shout has no brackets. With brackets you would call the function and store its result. Without them you store the function itself.
A function in one line
Sometimes you need a tiny function just once, usually to hand it to another function. Writing a full def for it feels heavy. A lambda is a small function written in a single expression.
def double(n):
return n * 2
double_lambda = lambda n: n * 2
print(double(5))
print(double_lambda(5))The two are equivalent. A lambda has three parts:
- the word
lambda - the parameters, before the colon
- one expression after the colon, which is automatically returned
There is no return keyword and no name. That is why lambdas are also called anonymous functions.
add = lambda a, b: a + b
is_even = lambda n: n % 2 == 0
initials = lambda first, last: f"{first[0]}.{last[0]}."
print(add(3, 4))
print(is_even(10))
print(initials("Ada", "Lovelace"))Storing a lambda in a variable like this is only for learning. In real code, if a function needs a name, use def.
Where lambdas shine: sort keys
The most common use of a lambda is the key argument of sorted(), min() and max(). The key is a function that says what to compare.
words = ["banana", "Kiwi", "apple", "cherry"] print(sorted(words)) print(sorted(words, key=lambda word: word.lower())) print(sorted(words, key=lambda word: len(word)))
Plain sorted() puts capital letters first. With a key, Python compares word.lower() or len(word) instead of the word itself, but still returns the original words.
Sorting records
This is where lambdas really earn their place: sorting a list of dictionaries or tuples by one field.
students = [
{"name": "Ada", "score": 92},
{"name": "Grace", "score": 85},
{"name": "Alan", "score": 95},
]
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
for student in by_score:
print(student["name"], student["score"])
best = max(students, key=lambda s: s["score"])
print("Top student:", best["name"])reverse=True sorts from highest to lowest.
Sorting by more than one thing
If the key returns a tuple, Python compares the first item, then uses the second to break ties.
team = [("Ravi", "Data"), ("Ana", "Web"), ("Mei", "Data"), ("Leo", "Web")]
ordered = sorted(team, key=lambda person: (person[1], person[0]))
print(ordered)The list is sorted by team first, and by name within each team.
When not to use a lambda
A lambda can contain only one expression. No loops, no if blocks with several lines, no assignments. If you need any of those, or the logic needs a moment's thought, write a named function with def. It is easier to read, test and reuse.
# Hard to read
grade = lambda s: "A" if s >= 90 else "B" if s >= 80 else "C" if s >= 70 else "F"
# Clearer
def grade(score):
if score >= 90:
return "A"
if score >= 80:
return "B"
if score >= 70:
return "C"
return "F"Common mistakes
Sort the products by price with a lambda, then print them.
products = [
("Laptop stand", 35),
("Webcam", 60),
("Mouse", 25),
("Headphones", 150),
]
# Sort the products by price, cheapest first, using sorted() with a lambda key.
# Then print each one as "name: price". Output must be exactly:
# Mouse: 25
# Laptop stand: 35
# Webcam: 60
# Headphones: 150
What does (lambda a, b: a * b)(3, 4) return?
Summary
- Functions are values: you can store them and pass them to other functions.
lambda params: expressionis a small, nameless function that returns its expression.- Lambdas are most useful as the
keyforsorted(),min()andmax(). - If the logic needs more than one simple expression, write a
deffunction.
Next: three built-in functions that pair naturally with lambdas.
Finished reading? Tick it off to track your progress.