Lambdas
Tiny one-line functions, and sorting by a key.
4 minute read
Big idea
A lambda is a tiny function with no name, written in one expression: lambda x: x * 2. It's most useful as a quick argument to another function, like sorted.
The idea
These two do the same thing:
def double(x):
return x * 2
double = lambda x: x * 2
lambda parameters: expression — the expression's value is returned automatically. No def, no return, no name needed.
double = lambda x: x * 2
add = lambda a, b: a + b
print(double(21))
print(add(3, 4))output
42
7Run and edit it in the app.
Storing a lambda in a variable like this is legal, but if you're naming it anyway, a def is clearer. Lambdas shine when the function is passed somewhere and used once.
Functions are values
In Python, a function can be passed to another function like any other value. sorted, min, and max accept a key function: it's called on each item, and the items are compared by what it returns.
words = ["banana", "kiwi", "apple", "fig"]
print(sorted(words))
print(sorted(words, key=len))
print(sorted(words, key=lambda w: w[-1]))output
['apple', 'banana', 'fig', 'kiwi']
['fig', 'kiwi', 'apple', 'banana']
['banana', 'apple', 'fig', 'kiwi']Run and edit it in the app.
- No key: alphabetical.
key=len: by length (lenis already a function — no lambda needed).key=lambda w: w[-1]: by the last letter.
Sorting records
players = [("Ada", 72), ("Ben", 95), ("Cy", 88)]
best = max(players, key=lambda p: p[1])
print(best)
ranked = sorted(players, key=lambda p: p[1], reverse=True)
print([name for name, score in ranked])What does it print? Show the answer
('Ben', 95)
['Ben', 'Cy', 'Ada']Run and edit it in the app.
map and filter
map(f, items) applies f to every item; filter(f, items) keeps items where f is truthy. Wrap them in list() to see the results:
nums = [1, 2, 3, 4]
list(map(lambda n: n * 10, nums)) # [10, 20, 30, 40]
list(filter(lambda n: n % 2 == 0, nums)) # [2, 4]
A comprehension usually reads better: [n * 10 for n in nums].
items = [("tea", 2.5), ("cake", 1.75), ("soup", 4.0)]
for name, price in sorted(items):
print(name, price)output
cake 1.75
tea 2.5
soup 4.0Run and edit it in the app.
Without a key, tuples sort by their first item — the name. Add key=lambda item: item[1].
What does sorted(["bb", "a", "ccc"], key=len) return?
Watch it
Think of it like
A sticky note with a quick instruction — "sort these by the last letter" — handed to a colleague, used once, and thrown away. A def is the laminated procedure you keep on the wall.
Key terms
- Lambda — A small anonymous function:
lambda x: x + 1. - key function — A function
sorted,min, andmaxuse to decide how to compare items. - Higher-order function — A function that takes another function as an argument.
Check yourself
What does (lambda x: x + 1)(4) give?
What does key= do in sorted(items, key=f)?
Can a lambda contain several statements?