Python Notes
Complete guide to Python lambda functions — syntax, use cases, usage with map/filter/sorted, and comparison with regular functions. Learn with practical examples.
Lambda is an anonymous function — a small function without a name that is written in a single line. Small task, small function!
1️⃣ Basic Lambda Syntax
# OUTPUT:
25
25
<class 'function'>
<class 'function'>
Namaste! 🙏
14
7
Raj Kumar Sharma2️⃣ Lambda with Conditions
| Score 95 | A+ |
| Score 83 | A |
| Score 71 | B |
| Score 55 | C |
3️⃣ Lambda with map() — Transformation
| Squares | [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] |
| Celsius | [0, 20, 37, 100] |
| Fahrenheit | [32.0, 68.0, 98.6, 212.0] |
| Original | ['rahul', 'priya', 'amit', 'sunita'] |
| Capitalized | ['Rahul', 'Priya', 'Amit', 'Sunita'] |
| Original prices | [100, 250, 500, 1000, 75] |
| After 10% off | [90.0, 225.0, 450.0, 900.0, 67.5] |
4️⃣ Lambda with filter() — Filtering
| All numbers | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] |
| Even only | [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] |
| Div by 3 | [3, 6, 9, 12, 15, 18] |
| Mixed | [-5, -2, 0, 3, 7, -1, 8, 12, -9] |
| Positive | [3, 7, 8, 12] |
| Anil | 72 |
| Chetan | 88 |
| Esha | 55 |
| Beena | 35 |
| Divya | 28 |
5️⃣ Lambda with sorted() and sort() — Custom Sorting
| Amit | ₹38,000 |
| Rahul | ₹45,000 |
| Rohan | ₹55,000 |
| Priya | ₹62,000 |
| Sunita | ₹75,000 |
| Sunita | ₹75,000 |
| Priya | ₹62,000 |
| Rohan | ₹55,000 |
| Rahul | ₹45,000 |
| Amit | ₹38,000 |
6️⃣ Lambda with reduce() — Aggregation
| Sum | 15 |
| Product | 120 |
| Maximum | 5 |
| Sentence | Python is awesome |
| 🛒 Cart Total | ₹1721 |
7️⃣ Immediately Invoked Lambda (IIFE)
8️⃣ Lambda as Callback / Event Handler
⚠️ Lambda ke Limitations
🏗️ Real-World: Data Processing Pipeline
| 💰 Total Revenue | ₹10,230 |
| 📦 Total Delivered | 4 |
| ⭐ Avg Order Value | ₹2,557 |
❓ Interview Questions
Q1: Can you name a lambda function?
# Technically yes, but not recommended
square = lambda x: x**2 # PEP8: use def instead
# Better:
def square(x): return x**2Q2: Can lambda have default arguments?
add = lambda x, y=10: x + y
print(add(5)) # 15
print(add(5, 3)) # 8Q3: Lambda function __name__ kya return karta hai?
f = lambda x: x
print(f.__name__) # '<lambda>'Q4: map() vs list comprehension — kaunsa better hai?
📋 Summary
🚀 Next: To learn Recursive Functions, read recursive-functions.mdx!⚠️ Common Mistakes
❌ Mistake 1: Writing multiple statements in lambda
# ❌ WRONG — Lambda only supports a single expression
# bad = lambda x: x = x + 1; print(x) # SyntaxError!
# ✅ RIGHT — Use regular def for multiple statements
def increment_and_print(x):
x = x + 1
print(x)
return x
increment_and_print(5)❌ Mistake 2: Assigning lambda to a variable (PEP8 violation)
# ❌ WRONG — PEP8 kehta hai lambda ko naam mat do
multiply = lambda x, y: x * y
# ✅ RIGHT — If you need a name, use def
def multiply(x, y):
return x * y
print(multiply(3, 4))❌ Mistake 3: Writing complex nested ternary in lambda
# ❌ WRONG — Hard to read
classify = lambda x: "Positive" if x > 0 else ("Zero" if x == 0 else ("Slightly Negative" if x > -5 else "Very Negative"))
# ✅ RIGHT — Use def for readability
def classify(x):
if x > 0: return "Positive"
elif x == 0: return "Zero"
elif x > -5: return "Slightly Negative"
else: return "Very Negative"
print(classify(-3))
print(classify(10))❌ Mistake 4: Lambda ke andar loop variable capture issue
❌ Mistake 5: Modifying in filter() instead of filtering
❌ Mistake 6: Lambda mein print() daal dena
❌ Mistake 7: reduce() mein initial value bhoolna
from functools import reduce
# ❌ WRONG — Empty list pe reduce without initial = TypeError!
try:
result = reduce(lambda a, b: a + b, [])
except TypeError as e:
print(f"Error: {e}")
# ✅ RIGHT — Provide an initial value for safety
result = reduce(lambda a, b: a + b, [], 0)
print(f"Safe result: {result}")✅ Key Takeaways
- 🔹 Lambda = Anonymous Function — A small function without a name, written in a single expression
- 🔹 Syntax:
lambda arguments: expression— No need to writereturn, it's implicit - 🔹 With map() — Use to transform each element (celsius to fahrenheit, price after discount)
- 🔹 With filter() — Use to filter elements based on a condition (even numbers, passed students)
- 🔹 With sorted() — Use
key=lambdato define custom sorting logic (salary, rating, price) - 🔹 With reduce() — To combine an entire list into a single value (sum, product, max)
- 🔹 Remember limitations — Lambda cannot have multiple statements, loops, try-except, or assignments
- 🔹 PEP8 Rule — Don't assign lambda to a variable; if you need a name, use
def - 🔹 Readability > Cleverness — If lambda looks confusing, write a regular function
- 🔹 IIFE Pattern —
(lambda x: x**2)(5)lets you immediately invoke without naming
❓ FAQ
Q1: What is the difference between a lambda function and a regular function?
Answer: Lambda is an anonymous (nameless) function written in just one expression. In a regular def function, you can have multiple statements, loops, exception handling, etc. Lambda is used when you have a small task to do in one place — like providing a key function in sorted(). Use a regular function when the logic is complex or the function needs to be reused.
Q2: Can you give multiple arguments to a lambda function?
Answer: Yes, absolutely! You can give unlimited arguments in lambda — separated by commas. Example: lambda a, b, c: a + b + c. Default arguments are also supported: lambda x, y=10: x + y. And you can use *args too: lambda *args: sum(args).
Q3: When should you use a lambda function and when not?
Answer: Use lambda when: (1) It's a simple one-liner expression, (2) You need a quick function with map/filter/sorted, (3) The function will only be used once. Don't use lambda when: (1) Logic is complex (2+ lines), (2) Error handling is needed, (3) The function needs to be reusable, (4) A docstring is needed.
Q4: Should you use map() or list comprehension?
Answer: Both do the same thing, but list comprehension is considered more Pythonic. [x2 for x in nums] is easier to read vs list(map(lambda x: x2, nums)). But when a function is already defined (like str.upper), map(str.upper, words) looks cleaner. The performance difference is negligible.
Q5: How to write if-else inside lambda?
Answer: Use the ternary operator in lambda: lambda x: "Even" if x % 2 == 0 else "Odd". But avoid nested ternary — lambda x: "A" if x>90 else ("B" if x>80 else "C") is not readable. In such situations, def is better.
Q6: Kya lambda recursion support karta hai?
Answer: Technically yes, but it's very tricky and impractical. Lambda is anonymous so calling itself is difficult. If you need recursion, always use a regular def function.
Q7: reduce() function Python 3 mein directly available hai?
Answer: No! In Python 3, reduce() is not built-in. To use it, you have to write from functools import reduce. Python moved it out of built-ins.
Q8: How to debug a lambda function?
Answer: Debugging lambda is difficult because: (1) Its name shows as <lambda> in tracebacks, (2) Setting breakpoints is tricky, (3) You can't easily add print statements. Tip: First convert complex lambda to a regular function, debug it, then if needed write it back as lambda.
🎯 Interview Questions
Q1: What is a lambda function? Explain its syntax.
Answer: Lambda is an anonymous (nameless) function created with the lambda keyword. Syntax: lambda arguments: expression. It evaluates only one expression and implicitly returns it. Example: lambda x, y: x + y returns the sum of two numbers. It's primarily used with higher-order functions like map(), filter(), sorted().
Q2: Lambda function ki limitations kya hain?
Answer: Lambda ki limitations:
- ❌ You can write only one expression — no multiple statements
- ❌ Assignment is not possible (
y = x * 2is invalid) - ❌ try-except cannot be written — error handling is impossible
- ❌ Loops (for/while) cannot be included
- ❌ Docstring cannot be added
- ❌ Debugging is difficult —
<lambda>appears in tracebacks - ❌ Complex nested logic unreadable ho jaata hai
Q3: What is the difference between map(), filter(), and reduce()?
Answer:
map(func, iterable)— Applies the function to each element and returns a new iterable. Used for transformation. Output length = input length.filter(func, iterable)— Keeps only elements where the function returnsTrue. Used for filtering. Output length ≤ input length.reduce(func, iterable)— Reduces the entire list to a single value by accumulating. Used for aggregation (sum, product, finding max/min).
Q4: How does closure work in lambda? Explain the loop variable trap.
Answer: Lambda accesses variables from the enclosing scope through closure. Problem: When creating lambdas in a loop, all lambdas share the same variable reference (late binding). Fix: Use a default argument.
This happens because lambda looks at the value of i at execution time, not definition time. A default argument captures the value at definition time.
Q5: What is the role of key=lambda in sorted()?
Answer: The key parameter of sorted() accepts a function that generates a comparison value for each element. Lambda is perfect here as you don't need a named function for a one-liner comparison logic.
The key function is called on each element, comparison happens based on the return value, and original elements remain untouched. Multiple criteria can be handled by returning tuples.
Q6: Lambda vs List Comprehension — performance comparison?
Answer: List comprehension is generally slightly faster than map() + lambda because:
- Lambda has function call overhead on every iteration
- List comprehension Python internally optimize karta hai
- Lekin difference negligible hai (microseconds level)
Rule of thumb: Readability first! Use list comprehension for simple transformations. When you need to pass an existing function (like str.upper), map() is cleaner.
Q7: What is a higher-order function? How does lambda relate to it?
Answer: Higher-order function wo function hai jo:
- Accepts a function as an argument, or
- Function return kare
map(), filter(), sorted(), reduce() are all higher-order functions. Lambda is their natural partner — for quickly providing throwaway functions.
Q8: How does IIFE (Immediately Invoked Function Expression) work in Python?
Answer: In the IIFE pattern, lambda is defined and called in a single line:
result = (lambda x, y: x**2 + y**2)(3, 4) # 25Use cases: Quick one-time calculations, complex default values, and when you don't want to create a temporary variable. Wrapping lambda in parentheses and calling it immediately.
Q9: Can you use *args and **kwargs in lambda?
Answer: Yes! Lambda supports both *args and **kwargs:
sum_all = lambda *args: sum(args)
print(sum_all(1, 2, 3, 4)) # 10
make_dict = lambda **kwargs: kwargs
print(make_dict(name="Rahul", age=25)) # {'name': 'Rahul', 'age': 25}But you can't do complex unpacking or multiple operations in lambda, so even with *args/**kwargs, keep the expression simple.
Q10: What is the most common use case of lambda in real-world projects?
Answer: In the real world, lambda is most commonly used for:
- Sorting —
sorted(employees, key=lambda e: e.salary) - DataFrame operations —
df.apply(lambda row: row.price * row.qty, axis=1) - Event handlers — GUI frameworks mein button callbacks
- API callbacks —
requests.get(url, hooks={'response': lambda r: print(r.status_code)}) - Dictionary sorting —
sorted(d.items(), key=lambda x: x[1])
In Pandas/Data Science, lambda is very frequently used with .apply(), .map(), .filter().
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Lambda Functions in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, functions, lambda, lambda functions in python
Related Python Master Course Topics