Lambda Functions
A lambda function is a small, nameless function written in a single expression. Lambdas are handy when you need a quick function for a moment, most often as the key for sorting or as an argument to another function, and writing a full def would feel heavy.
Syntax
lambda parameters: expression
A lambda takes any number of parameters, evaluates one expression and automatically returns its result. There is no return keyword and no function name. These two definitions behave the same:
def square(x):
return x * x
square_lambda = lambda x: x * x
print(square(6))
print(square_lambda(6))
add = lambda a, b: a + b
print(add(3, 4))
Assigning a lambda to a name, as above, is fine for learning, but Python's style guide (PEP 8) recommends using def whenever you want a named function. A def gives clearer error messages and room for a docstring. Lambdas are at their best when passed directly into another function, as in the rest of this page.
Sorting with a key
The most common use of a lambda is the key argument of sorted(), sort(), max() and min(). The key function is called on each item, and its result decides the order. (You met key=len on List Methods.)
students = [("Amina", 78), ("Brian", 64), ("Chebet", 91)]
by_score = sorted(students, key=lambda s: s[1])
print(by_score)
best_first = sorted(students, key=lambda s: s[1], reverse=True)
print(best_first)
print(max(students, key=lambda s: s[1]))
Each student is a tuple, and lambda s: s[1] says "sort by the item at index 1", the score.
Sorting a dictionary by its values
prices = {"tea": 30, "mandazi": 10, "chapati": 20}
cheapest_first = sorted(prices.items(), key=lambda item: item[1])
print(cheapest_first)
print(dict(cheapest_first))
Sorting by more than one thing
Return a tuple from the key to sort by several criteria: Python compares the first items, then the second if there's a tie.
fruits = ["kiwi", "fig", "mango", "date", "pear"] print(sorted(fruits, key=lambda w: (len(w), w)))
The words are ordered by length first; the three four-letter words are then ordered alphabetically.
map() and filter()
map(function, iterable) applies a function to every item. filter(function, iterable) keeps only the items for which the function returns a true value. Both give back a lazy object, so wrap them in list() to see the results.
prices = [100, 250, 80] doubled = list(map(lambda p: p * 2, prices)) print(doubled) over_90 = list(filter(lambda p: p > 90, prices)) print(over_90)
The same results with comprehensions are [p * 2 for p in prices] and [p for p in prices if p > 90]. Many Python programmers find comprehensions easier to read, so choose whichever is clearer to you and your team.
Conditional expressions in a lambda
A lambda can't contain statements such as if blocks, but it can use a one-line conditional expression.
label = lambda marks: "Pass" if marks >= 50 else "Fail" print(label(67)) print(label(38))
Limitations
- Only a single expression: no assignments, loops,
returnor multiple statements. - No name and no docstring, which makes error tracebacks less helpful (they show
<lambda>). - Long lambdas are hard to read. If it doesn't fit comfortably on one line, write a
def.
Writing return inside a lambda, as in lambda x: return x * 2. That's a SyntaxError: the expression's value is returned automatically, so just write lambda x: x * 2.
Forgetting that map() and filter() are lazy. print(map(lambda p: p * 2, prices)) shows something like <map object at 0x...> instead of numbers. Convert with list() first, and remember that a map or filter object can only be looped over once.
Key points
lambda params: expressioncreates a small anonymous function that returns the expression.- Lambdas shine as
keyfunctions forsorted(),max()andmin(). map()andfilter()take a function and return lazy results; wrap them inlist().- Use
deffor anything longer than a single, clear expression.
Tip: use the ← and → keys to move between pages.
