PY-101 ยท Functions
Lambda functions
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A lambda is a small, unnamed function written in one line: lambda x: x * 2 takes x and returns x * 2. It is used where a short function is needed once, most often as the key for sorted(), max() or min(). For anything longer than one expression, use def.
- Write a lambda
- Sort with key=lambda
- Know when def is better
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
products = [("pen", 20), ("bag", 450), ("book", 120)]cheap_first = sorted(products, key=lambda p: p[1])print(cheap_first)priciest = max(products, key=lambda p: p[1])print("Most expensive:", priciest[0])
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
[('pen', 20), ('book', 120), ('bag', 450)]
Most expensive: bag ๐ฏ Sort words by length, shortest first, using sorted() with a lambda key. Print the result.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
print(sorted(words, key=lambda w: len(w)))
- The problemYou have a list of products and want them sorted by price, not by name. sorted() needs a tiny rule saying "look at the price". A lambda is that rule.
- The Python idea
lambda parameters: expressionA lambda is a small, unnamed function written in one line: lambda x: x * 2 takes x and returns x * 2. - In real lifeLeaderboards sort players by score with key=lambda p: p.score, often with reverse=True for highest first.
Start with a question
You have a list of products and want them sorted by price, not by name. sorted() needs a tiny rule saying "look at the price". A lambda is that rule.
Sorting and picking the best item by some rule is constant in real code, and lambdas keep those rules right where they are used.
Explain it like I'm 10
A lambda is a sticky note with one instruction on it, handed to someone else to use. No name, no fuss.
The technical explanation
lambda x: x * 2 is a function that returns x * 2. It has no return keyword; the expression is returned.
sorted(items, key=lambda p: p[1]) sorts by the second element of each item.
A lambda can take several parameters: lambda a, b: a + b.
Syntax
lambda parameters: expression
sorted(items, key=lambda item: ...) Real-world scenario
Leaderboards sort players by score with key=lambda p: p.score, often with reverse=True for highest first.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Recursion โQuestions people ask
When should I use lambda in Python?
For a short, one-off function passed to another function, especially key= in sorted, min and max. Use def for anything you name or reuse.
Is lambda faster than def?
No. They create the same kind of function object. The difference is only how you write it.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner When should I use lambda in Python?
For a short, one-off function passed to another function, especially key= in sorted, min and max. Use def for anything you name or reuse.
beginner Is lambda faster than def?
No. They create the same kind of function object. The difference is only how you write it.
intermediate What does (lambda x: x + 1)(4) return?
5. It adds 1 to 4.
intermediate Can a lambda contain several statements?
No, one expression only. A lambda is a single expression.
Quick revision
Remember
- Write a lambda
- Sort with key=lambda
- Know when def is better
- If you are tempted to give a lambda a name (
double = lambda x: x * 2), write a normal def instead. It is clearer and shows up properly in error messages.
Syntax
lambda parameters: expression
sorted(items, key=lambda item: ...) Official documentation
- Lambda expressions (docs.python.org)
- Sorting HOW TO (docs.python.org)