What is a lambda function in Python, and what are its limits?
A lambda is a small anonymous function written as lambda args: expression. It contains a single expression, returns its value automatically and cannot hold statements. It is handy as a short key or callback.
Explain it simply
A def function is like a printed form with a title. A lambda is a sticky note: a throwaway instruction like "double this", needed once and not worth naming.
The body is only one expression. There is no return, no assignment statements, no loops. If you need those, write a normal def.
Example
double = lambda x: x * 2
print(double(4)) # Output: 8
students = [("Asha", 80), ("Dev", 95), ("Ira", 70)]
students.sort(key=lambda s: s[1])
print(students[0]) # Output: ('Ira', 70)
print(list(map(lambda n: n ** 2, [1, 2, 3]))) # Output: [1, 4, 9]
print(list(filter(lambda n: n % 2 == 0, range(7)))) # Output: [0, 2, 4, 6]
grade = lambda m: "pass" if m >= 35 else "fail"
print(grade(40)) # Output: passWhat to say in the interview
"A lambda is an anonymous function limited to one expression, whose value is returned implicitly. I use it for short keys in sorted, min and max, and for simple callbacks. If I'm assigning a lambda to a name, a def is clearer, since it has a proper name in tracebacks and can have a docstring."
Common mistakes
- Cramming complex logic into a lambda, which hurts readability.
- Assigning a lambda to a variable only to call it like a normal function (PEP 8 prefers
def).