Lambda Functions
A lambda function is a small function written in a single line, without a name. You use it when a function is needed for just a moment, most often to tell sorted(), min() or max() how to compare things.
In this lesson you will learn the lambda syntax, the places where it really helps, and the cases where an ordinary def function is the better choice.
The lambda syntax
A lambda has the keyword lambda, then the parameters, a colon, and one expression. The value of that expression is returned automatically; you never write return.
def add_gst(price):
return price * 1.18
add_gst_lambda = lambda price: price * 1.18
print(add_gst(500))
print(add_gst_lambda(500))
print((lambda a, b: a + b)(45, 38))590.0 590.0 83
The first two functions do exactly the same thing. The last line creates a lambda and calls it immediately, just to show that a lambda is a real function. In real code you would not do either of these: if a function needs a name, write it with def. The Python style guide (PEP 8) says so too, because a def function has a proper name in error messages and can have a docstring.
So where are lambdas useful? When you pass a function into another function.
Sorting with a key function
sorted() and the list method sort() accept a key argument. The key is a function that Python calls on every item; items are then sorted by whatever that function returns. A lambda is the perfect way to write a short key.
scores = [("Aarav", 78), ("Priya", 92), ("Rohan", 65), ("Meera", 88)]
by_marks = sorted(scores, key=lambda student: student[1], reverse=True)
print(by_marks)
by_name_length = sorted(scores, key=lambda student: len(student[0]))
print(by_name_length)[('Priya', 92), ('Meera', 88), ('Aarav', 78), ('Rohan', 65)]
[('Aarav', 78), ('Priya', 92), ('Rohan', 65), ('Meera', 88)]In the first call, the lambda returns the marks, so the list is ordered by marks, highest first. In the second it returns the length of the name. All four names have five letters, so they tie, and Python keeps tied items in their original order. This is called a stable sort.
The same key idea works with min() and max(). Here the items are dictionaries (see Dictionaries):
phones = [
{"model": "Nova 5", "price": 14999, "rating": 4.2},
{"model": "Zip X", "price": 9999, "rating": 3.9},
{"model": "Orbit 12", "price": 21999, "rating": 4.6},
]
cheapest = min(phones, key=lambda p: p["price"])
best = max(phones, key=lambda p: p["rating"])
print("Cheapest:", cheapest["model"])
print("Best rated:", best["model"])
for p in sorted(phones, key=lambda p: (-p["rating"], p["price"])):
print(p["model"], p["rating"], p["price"])Cheapest: Zip X Best rated: Orbit 12 Orbit 12 4.6 21999 Nova 5 4.2 14999 Zip X 3.9 9999
The last key returns a tuple. Python compares tuples item by item, so the phones are sorted by rating (the minus sign makes it highest first) and then by price for any ties.
map() and filter()
map(function, items) applies a function to every item. filter(function, items) keeps only the items for which the function returns a true value. Both return lazy objects, so wrap them in list() to see the result.
prices = [120, 450, 80, 999, 300]
with_gst = list(map(lambda p: round(p * 1.18), prices))
expensive = list(filter(lambda p: p > 250, prices))
print(with_gst)
print(expensive)
# The same results with list comprehensions
print([round(p * 1.18) for p in prices])
print([p for p in prices if p > 250])[142, 531, 94, 1179, 354] [450, 999, 300] [142, 531, 94, 1179, 354] [450, 999, 300]
Most Python programmers find the comprehension version easier to read, so prefer it. You will still meet map() and filter() in other people's code, and map() is handy with an existing function, as in list(map(int, ["4", "7"])).
Lambdas in a dictionary
Because a lambda is a value, you can store it in a list or dictionary. This lets you choose an action by looking it up instead of writing a long if/elif chain.
operations = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"x": lambda a, b: a * b,
}
for symbol in ["+", "-", "x"]:
print(f"12 {symbol} 4 =", operations[symbol](12, 4))12 + 4 = 16 12 - 4 = 8 12 x 4 = 48
Common mistakes
- Calling the key instead of passing it.
sorted(names, key=len())is wrong;len()runs immediately and fails. Pass the function itself:key=lenorkey=lambda n: len(n). - Writing
returninside a lambda.lambda x: return x * 2is aSyntaxError. The expression is returned automatically. - Squeezing complex logic into one line. If a lambda needs nested conditions or is hard to read, write a named
deffunction and pass its name as the key. - Lambdas created in a loop. They look up loop variables when they run, not when they are created, which can surprise you. Scope & Closures explains why.
Key points
lambda params: expressioncreates a small unnamed function that returns the expression.- Lambdas are best as short arguments to other functions, especially
key=insorted(),sort(),min()andmax(). - A key can return a tuple to sort by several things at once.
- Prefer list comprehensions over
map()andfilter()with lambdas for readability. - If a function needs a name, a docstring or more than one expression, use
def.
Exercise
Here is a list of trains as tuples of (name, departure hour, fare): ("Shatabdi", 6, 1250), ("Duronto", 22, 1890), ("Intercity", 9, 450), ("Garib Rath", 21, 760). Using lambdas, print the trains sorted by fare from cheapest to most expensive, then print the name of the train that leaves earliest, and finally print a list of only the trains that leave after 8 pm (hour 20 or later).
Show solution
trains = [
("Shatabdi", 6, 1250),
("Duronto", 22, 1890),
("Intercity", 9, 450),
("Garib Rath", 21, 760),
]
print(sorted(trains, key=lambda t: t[2]))
print(min(trains, key=lambda t: t[1])[0])
print(list(filter(lambda t: t[1] >= 20, trains)))[('Intercity', 9, 450), ('Garib Rath', 21, 760), ('Shatabdi', 6, 1250), ('Duronto', 22, 1890)]
Shatabdi
[('Duronto', 22, 1890), ('Garib Rath', 21, 760)]Each lambda picks one item from the tuple: the fare for sorting, the hour for min() and the hour again for the filter. The last line could also be written as [t for t in trains if t[1] >= 20].
Quick Quiz
1. What does lambda n: n * 3 return when called with 4?
A lambda returns the value of its expression automatically, so the result is 12.
2. Which is the best use of a lambda?
Lambdas shine as short, throwaway functions passed to other functions, such as sort keys.
3. What does sorted(words, key=len) do?
The key function is called on each item, so words are ordered by len(word).
4. Which of these is NOT allowed inside a lambda?
A lambda holds a single expression; assignment with = is a statement.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
