Lesson 6 of 10
A lambda is a small function written inline, without a name. These two are equivalent:
def double(x):
return x * 2
double_lambda = lambda x: x * 2
print(double(5))
print(double_lambda(5))
The syntax is lambda parameters: expression. There is no def, no name, no return — the
expression's value is the return value.
The rules
A lambda can take any number of parameters but must be a single expression:
add = lambda a, b: a + b
print(add(3, 5))
is_even = lambda n: n % 2 == 0
print(is_even(4))
greet = lambda name="world": f"Hello, {name}!"
print(greet())
No statements are allowed — no if blocks, no loops, no multiple lines. You can use a
conditional expression, which is a single expression:
sign = lambda n: "positive" if n > 0 else "not positive"
print(sign(5))
print(sign(-5))
Don't assign lambdas to names
This works but is considered poor style:
double = lambda x: x * 2
If you're giving it a name, just use def — you get a proper function name in tracebacks,
somewhere to put a docstring, and room to grow. Python's own style guide says exactly this.
Where lambdas actually belong
Lambdas earn their keep when a function needs a small function as an argument, used once.
The classic case is sorted() with a key:
people = [
{"name": "Ada", "age": 36},
{"name": "Grace", "age": 45},
{"name": "Alan", "age": 41},
]
by_age = sorted(people, key=lambda p: p["age"])
for person in by_age:
print(person["name"])
key takes a function that, given one item, returns the value to sort by. Writing a whole
def get_age(p): return p["age"] for something used once and thrown away is noise — the lambda
sits right where it's used and reads cleanly.
You'll meet more of these in the next lesson.
Try it yourself
Sort the list of dictionaries by age and print each name in order.
Checkpoint
lambda params: expressionis an unnamed one-expression function.- The expression's value is returned automatically.
- No statements allowed — but conditional expressions are fine.
- Use
deffor anything you name; uselambdafor throwaway arguments likekey=.
Questions about this lesson
Log in to ask a question.