After this lesson you can write a one-line function with lambda, use it to sort data by a chosen field, and recognise when a lambda has become too clever.
What a lambda is
A lambda is a function without a name, written on a single line. The shape is the word lambda, the parameters, a colon, and one expression. The value of that expression is what the function returns.
Here is an ordinary function and its lambda twin:
def double(x):
return x * 2
double_lambda = lambda x: x * 2
print(double(4))
print(double_lambda(4))
print(type(double_lambda))8
8
<class 'function'>They behave the same way. Python style guides prefer def when a function gets a name like this, because a def shows the name in error messages and can hold a docstring. The real value of lambda is when you need a tiny function once, in the middle of another call, and a full def would be noise.
Calling it immediately
Because a lambda is an expression, you can create and call it in one go. This is rarely useful in real code but it shows what a lambda is:
print((lambda a, b: a + b)(3, 4))7Lambdas can have no parameters, several parameters, or default values:
greet = lambda name="friend": "Hello, " + name
print(greet())
print(greet("Asha"))Hello, friend
Hello, AshaThe best use: the key argument
Functions such as sorted, min and max accept a key function that says what to compare. Say a shop keeps products as pairs of name and price:
products = [("tea", 120), ("coffee", 250), ("milk", 60)]
print(sorted(products))
print(sorted(products, key=lambda item: item[1]))
print(min(products, key=lambda item: item[1]))
print(max(products, key=lambda item: item[1]))[('coffee', 250), ('milk', 60), ('tea', 120)]
[('milk', 60), ('tea', 120), ('coffee', 250)]
('milk', 60)
('coffee', 250)The first line sorts by name, since tuples compare element by element. The key version sorts by price, because for each tuple the lambda picks out the second element. The function is used once, so naming it would add nothing.
The same idea works with dictionaries:
students = [
{"name": "Asha", "marks": 82},
{"name": "Ben", "marks": 91},
{"name": "Chloe", "marks": 77},
]
best_first = sorted(students, key=lambda s: s["marks"], reverse=True)
print([s["name"] for s in best_first])['Ben', 'Asha', 'Chloe']Conditional expressions
A lambda cannot contain statements such as a full if block, but it can use the one-line conditional expression, which is itself an expression:
grade = lambda marks: "pass" if marks >= 40 else "fail"
print(grade(55))
print(grade(30))pass
failLambdas as callbacks
You can also keep lambdas in a data structure, which gives a simple way to choose behaviour by name:
operations = {
"add": lambda a, b: a + b,
"multiply": lambda a, b: a * b,
}
print(operations["add"](6, 7))
print(operations["multiply"](6, 7))13
42When not to use lambda
If you need more than one expression, a loop, an assignment or an error handler, write a def. If the lambda needs a comment to explain it, use def with a good name. Compare:
prices = [100, 250, 80]
with_tax = list(map(lambda p: round(p * 1.18, 2), prices))
print(with_tax)[118.0, 295.0, 94.4]This is fine because it is short. When it gets longer than about one readable line, give it a name instead.
Lambdas and default values in loops
Lambdas look at variables when they are called, not when they are created. This surprises people who build several lambdas in a loop:
multipliers = [lambda x: x * n for n in [1, 2, 3]]
print([f(10) for f in multipliers])
fixed = [lambda x, n=n: x * n for n in [1, 2, 3]]
print([f(10) for f in fixed])[30, 30, 30]
[10, 20, 30]In the first list every lambda uses the final value of n, which is 3, so all three give 30. The second version stores the current n as a default value, giving the intended 10, 20 and 30. You will not need this trick often, but it explains an odd bug when you meet it.
Common mistakes
- Writing return inside a lambda. The expression is returned automatically, and
returnis a syntax error there. - Putting parentheses round the parameters. Write
lambda a, b: a + b, notlambda (a, b): a + b. - Trying to put statements in it. Assignments and multi-line logic are not allowed.
- Squeezing complex logic into one line. Readability beats cleverness every time.
- Forgetting it is still a function. Without parentheses and arguments you get the function object, not a result.
Here is the first mistake in action:
bad = lambda a, b: return a + bSyntaxError: invalid syntaxExercise
You have the list words = ["banana", "fig", "cherry", "kiwi"]. Use sorted with a lambda key to sort the words by length, shortest first. Then sort them by their last letter.
Show one possible answer
words = ["banana", "fig", "cherry", "kiwi"]
print(sorted(words, key=lambda w: len(w)))
print(sorted(words, key=lambda w: w[-1]))['fig', 'kiwi', 'banana', 'cherry']
['banana', 'fig', 'kiwi', 'cherry']Key points
- A lambda is a small function written as one expression: lambda arguments: expression.
- It returns the value of its expression automatically. There is no return keyword.
- Lambdas are mostly used inline, for example as the key for sorted, min and max.
- A lambda cannot hold several statements. Use def for anything longer than a single simple expression.
- Assigning a lambda to a name is legal but def is the clearer style.