Lambda Functions in Python — Python Technical Interview Questions & Answers
Lambda Functions in Python
Lambda Functions in Python
- lambda is a one-line function without a def name. Shape: lambda x: x * x. Useful as a key= in sorted, or a tiny map/filter. square = lambda n: n * n then square(5) is 25. Keep it tiny. If you need two statements, write a normal def. Complex lambda looks clever and reads badly.
- Viva: “anonymous one-line function”. Then sorted(students, key=lambda s: s["marks"]). Prefer def when the logic has a name worth saying out loud.
- Lambda Functions in Python — output: 5 then ['Asha', 'Neha', 'Ravi'] (or same lengths stay). add is a tiny function.
lambda a, b: a + b
│ (2, 3)
▼
5Technical Interview Tip: lambda with sorted key idea.
Code Examples for Lambda Functions in Python
Example
# lambda
add = lambda a, b: a + b
print(add(2, 3))
print(sorted(["Neha", "Asha", "Ravi"], key=lambda s: len(s)))
Lambda Functions in Python — output: 5 then ['Asha', 'Neha', 'Ravi'] (or same lengths stay). add is a tiny function.
How to Explain Lambda Functions in Python to an Interviewer
Explain Lambda Functions as if you are teaching a junior — definition, then one tiny script.
Tiny anonymous function. Single expression.
What does the example print, and why?
Lambda Functions in Python — output: 5 then ['Asha', 'Neha', 'Ravi'] (or same lengths stay)
What mistake do freshers make with Lambda Functions?
key= in sorted.