Lambda Functions
Lambda Functions
🎯 By the end of this lesson
After reading this lesson, you will be able to confidently do the following 3 things.
- ▸✅ lambda + map / filter / sorted key argument
- ▸✅ Extract a complex lambda into a named function
- ▸✅ Fix arguments with functools.partial
Keep the learning goals as a checklist — close the lesson once you can answer all of them.
5 lambda patterns — code + output
lambda = an anonymous one-liner function. Use it when you need a short function right there on the spot.
1. def vs lambda — same function
lambda parameters: expression — return is implicit.
2. Real use case — sorted() key
key=lambda x: ... is the most common use of lambda. A function used once and thrown away.
3. Combined with map and filter
⚠️ However, list comprehension is more Pythonic — [x*x for x in numbers].
4. dict sorting — by value
5. Bad example — overusing lambda
Rule: Use lambda only when you use it once, right there. If you need a name, use def.
One-line summary
Key takeaway: A short, single-use function with no name. If it gets long, use def.
💡 Key points
1. Lambda supports only a single expression (statements are not allowed)
2. For complex logic, a regular function is recommended
3. Useful as the key argument in sorted(), max(), min()
Python is used across many domains thanks to its concise, readable syntax. As an interpreted language, it can be executed immediately in a REPL environment. Follow the PEP 8 coding style guide and use Black/autopep8 for automatic formatting. Type hints improve code readability and IDE support. Use pip for package management and venv/conda for virtual environments.
🐍 Try it yourself — Lambda Functions
🤖 Try asking AI like this
Knowing the concepts in this lesson lets you give specific instructions to AI. Instead of a vague 'fix this,' you make vocabulary-driven requests — and that's where token savings begin.
- ▸'Add type hints + a docstring to this function'
- ▸'Remove the side effects (global variable mutation) from this function and turn it into a pure function'
Why this reduces tokens
Without understanding the concepts, even after receiving an AI response you have to ask 'What does that mean?' again. That follow-up question is what eats your tokens. Learn the concept once and the conversation ends in one go.