Python Lambda Functions Explained with Examples
A lambda is a small function written in one line, with no name and no def. Use it where Python wants a function for a moment, such as a sort key.
Read Defining functions and Sorting first.
Write a lambda
Write lambda, the parameters, a colon, then one expression. The lambda
returns the value of that expression.
double = lambda n: n * 2
print(double(4))
def double_def(n):
return n * 2
print(double_def(4))
add = lambda a, b: a + b
print(add(3, 4))
double and double_def both print 8. A lambda has no return: the
expression after the colon is the result. Separate two or more parameters
with commas, as in add.
Sort with a lambda key
sorted() calls its key function on each item and sorts by the result.
A lambda lets you write that function right where you use it.
names = ["maya", "Bo", "alexandra", "Cy"]
print(sorted(names))
print(sorted(names, key=lambda name: name.lower()))
Plain sorted() puts capital letters first. The lambda compares the
lowercase version of each name, so the order ignores capitals.
Sort pairs by the second value
A list of pairs sorts by the first value unless you say otherwise. Use a lambda that picks out the part you want to sort by.
scores = [("Ada", 12), ("Ben", 31), ("Cy", 20)]
ranking = sorted(scores, key=lambda pair: pair[1], reverse=True)
print(ranking)
pair[1] is the score in each pair. reverse=True puts the highest score
first.
Pick the best with max() and min()
max() and min() take a key too. They return the item, not the key
value.
scores = {"Ada": 12, "Ben": 31, "Cy": 20}
print(max(scores, key=lambda name: scores[name]))
print(min(scores, key=lambda name: scores[name]))
Looping over a dictionary gives its keys, so max() returns a name. The
lambda looks up each name's score to compare them.
Note: A lambda holds one expression only: no loops, no assignments, no
statements. Do not store a lambda in a variable to reuse it in real code.
Write a def with a clear name instead. The double example above is only
for comparing the two.
See also: map() and filter(), Parameters and return.
Your turn
Print words sorted by their last letter. Use a lambda as the key.
words = ["cat", "dog", "bee", "ant"]
# add one line: print words sorted with a lambda key that gives the last letter
Expected output
['bee', 'dog', 'cat', 'ant']