Chapter: Lambda Function in Python
Complete reference guide covering Anonymous functions, Syntax, Conditional expressions, map(), filter(), sorted(), rules, and interview answers.
1. What is a Lambda Function?
A Lambda Function is a small, anonymous (nameless) function in Python. It is defined using the lambda keyword instead of the traditional def keyword.
Easy English Explanation
- Anonymous: Does not require a formal name like standard functions.
- Single Operation: Best suited for quick, small, one-line calculations.
- Inline Use: Frequently passed directly into built-in functions like map(), filter(), and sorted().
Hinglish Explanation
- Anonymous Function: Ek aisa function jiska koi normal naam nahi hota.
- Kaha Use Hoga: Jab hume thode se time ke liye ek simple si line ka function chahiye hota hai.
- Short & Crisp: Code neat ho jaata hai aur alag se def likhne ki zaroorat nahi padti.
add = lambda a, b: a + b result = add(10, 20) print(result)
Line-by-Line Code Breakdown
| Line | Code Snippet | Easy English Explanation | Hinglish Explanation |
|---|---|---|---|
| 1 | add = lambda a, b: a + b | Creates a lambda function with parameters a and b that evaluates a + b, assigning it to variable add. | lambda keyword se ek function banakar add variable me save kiya jo a + b ka sum return karta hai. |
| 2 | result = add(10, 20) | Calls the lambda function via variable add passing arguments 10 and 20. | add(10, 20) call karke result (30) ko variable result me store kiya. |
| 3 | print(result) | Prints the calculated sum (30) to the screen. | Result (30) ko screen par print kiya. |
2. Syntax of a Lambda Function
Syntax Formula: lambda arguments : expression
Component Analysis
- lambda: Keyword used to start creating the anonymous function.
- arguments: Input variables separated by commas (e.g. x or a, b).
- :: Separator colon dividing inputs from the operation.
- expression: Single line of code evaluated and automatically returned.
Syntax ka Breakdown
- lambda: Ye Keyword function ko start karta hai.
- arguments: Wo variables jo inputs ki tarah milenge.
- :: Separator colon jo input aur logic ko alag karta hai.
- expression: Wo calculation jiska result automatically return hoga.
square = lambda x: x * x print(square(25))
3. Basic Math Operations with Lambda
add = lambda a, b: a + b
subtract = lambda a, b: a - b
multiply = lambda a, b: a * b
divide = lambda a, b: a / b
print("Addition:", add(10, 20))
print("Subtraction:", subtract(20, 8))
print("Multiplication:", multiply(5, 4))
print("Division:", divide(20, 5))
Subtraction: 12
Multiplication: 20
Division: 4.0
4. Lambda Function with Conditional (If-Else) Expressions
Lambda functions can incorporate ternary operators for conditional logic.
Ternary Syntax: lambda arguments: value_if_true if condition else value_if_false
check_even = lambda x: x % 2 == 0
check_even_odd_str = lambda x: "Even" if x % 2 == 0 else "Odd"
maximum = lambda a, b: a if a > b else b
minimum = lambda a, b: a if a < b else b
print("Is 10 Even?:", check_even(10))
print("7 is:", check_even_odd_str(7))
print("Max of 10 & 20:", maximum(10, 20))
print("Min of 10 & 20:", minimum(10, 20))
7 is: Odd
Max of 10 & 20: 20
Min of 10 & 20: 10
Line-by-Line Code Breakdown
| Line | Code Snippet | Easy English Explanation | Hinglish Explanation |
|---|---|---|---|
| 1 | check_even = lambda x: x % 2 == 0 | Returns boolean True if remainder after dividing by 2 is 0. | Agar 2 se divide karne par remainder 0 aae to True return karta hai. |
| 2 | lambda x: "Even" if x % 2 == 0 else "Odd" | Uses ternary operator to return string "Even" or "Odd". | Ternary expression: Condition true hone par "Even" aur false hone par "Odd" deta hai. |
| 3 | maximum = lambda a, b: a if a > b else b | Compares a and b and returns the larger value. | Agar a bada hai to a return karega, nahi to b. |
5. Normal Function vs Lambda Function
| Feature | Normal Function (def) | Lambda Function (lambda) |
|---|---|---|
| Keyword | Defined using def | Defined using lambda |
| Name | Has an explicit function name | Anonymous (nameless unless assigned to variable) |
| Statements | Can contain multiple statements, loops & blocks | Can only contain a single expression |
| Return Value | Requires explicit return statement | Implicitly/automatically returns expression result |
| Docstrings | Supports docstrings ("""doc""") | Does not support docstrings |
| Use Case | Complex, multi-step logic & large workflows | Quick inline operations, map/filter/sorted callbacks |
6. Lambda Function with map()
The map() function applies a given function to every item of an iterable (e.g. list) and returns a map object (convertible to list).
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
doubled = list(map(lambda x: x * 2, numbers))
names = ["gagan", "rahul", "aman"]
upper_names = list(map(lambda name: name.upper(), names))
print("Original Numbers:", numbers)
print("Squares:", squares)
print("Doubled:", doubled)
print("Uppercase Names:", upper_names)
Squares: [1, 4, 9, 16, 25]
Doubled: [2, 4, 6, 8, 10]
Uppercase Names: ['GAGAN', 'RAHUL', 'AMAN']
Line-by-Line Code Breakdown
| Line | Code Snippet | Easy English Explanation | Hinglish Explanation |
|---|---|---|---|
| 2 | list(map(lambda x: x * x, numbers)) | Applies x * x to each element in numbers and collects results into a new list. | map() function list ke har ek number par lambda (square) lagakar nayi list banata hai. |
| 6 | list(map(lambda name: name.upper(), names)) | Transforms each string in list names to uppercase format. | List ke har naam ko uppercase me convert karne ke liye name.upper() lambda map karta hai. |
7. Lambda Function with filter()
The filter() function filters elements of an iterable based on a boolean function condition. Only elements where the function returns True are retained.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
odds = list(filter(lambda x: x % 2 != 0, numbers))
print("Evens:", evens)
print("Odds:", odds)
Odds: [1, 3, 5, 7, 9]
Line-by-Line Code Breakdown
| Line | Code Snippet | Easy English Explanation | Hinglish Explanation |
|---|---|---|---|
| 2 | list(filter(lambda x: x % 2 == 0, numbers)) | Evaluates each number; retains only those where x % 2 == 0 is True. | filter() sirf unhi numbers ko chun-kar rakhta hai jo even condition ko pass karte hain. |
8. Lambda Function with sorted()
The sorted() function can use a lambda function as its key parameter to customize sorting logic (e.g. sorting a list of tuples by second element).
students = [
("Gagan", 85),
("Rahul", 70),
("Aman", 90)
]
sorted_asc = sorted(students, key=lambda x: x[1])
sorted_desc = sorted(students, key=lambda x: x[1], reverse=True)
print("Ascending Marks:", sorted_asc)
print("Descending Marks:", sorted_desc)
Descending Marks: [('Aman', 90), ('Gagan', 85), ('Rahul', 70)]
Line-by-Line Code Breakdown
| Line | Code Snippet | Easy English Explanation | Hinglish Explanation |
|---|---|---|---|
| 7 | sorted(students, key=lambda x: x[1]) | Passes lambda specifying x[1] (the mark score in tuple) as sorting criterion. | key=lambda x: x[1] se sorting tuple ke second element (marks) ke base par hoti hai. |
| 8 | reverse=True | Sorts in descending order (highest score first). | reverse=True se descending order (sabse zyada marks pehle) me list sort hoti hai. |
9. Important Rules of Lambda Functions
Essential Rules
- Must use the lambda keyword.
- Can accept multiple parameters separated by commas.
- Must contain exactly ONE expression.
- Automatically returns the expression value.
- Cannot contain statements like return, pass, or assignments (=).
Zaroori Rules
- lambda keyword likhna compulsory hai.
- Multiple arguments de sakte hain (a, b, c).
- Sirf aur sirf EK single expression ho sakta hai.
- Result automatic return hota hai.
- Kabhi bhi return keyword mat likhna (e.g. lambda a,b: return a+b WRONG hai).
10. Important Interview Question & Answer
Q: What is a Lambda Function in Python?
Answer: A lambda function is a small anonymous function defined using the lambda keyword. It can take any number of positional or keyword arguments, but can only have a single expression which is automatically evaluated and returned. It is primarily used for short-lived operations as callback arguments in functions like map(), filter(), and sorted().
11. 10 Core Lambda Code Examples
square = lambda x: x * x
print("1. Square of 5:", square(5))
cube = lambda x: x ** 3
print("2. Cube of 3:", cube(3))
add = lambda a, b: a + b
print("3. Add 10 & 20:", add(10, 20))
sub = lambda a, b: a - b
print("4. Subtract 20 & 5:", sub(20, 5))
mult = lambda a, b: a * b
print("5. Multiply 5 & 6:", mult(5, 6))
div = lambda a, b: a / b
print("6. Divide 20 & 4:", div(20, 4))
is_even = lambda x: x % 2 == 0
print("7. Is 10 Even?:", is_even(10))
is_odd = lambda x: x % 2 != 0
print("8. Is 9 Odd?:", is_odd(9))
max_val = lambda a, b: a if a > b else b
print("9. Max of 10 & 20:", max_val(10, 20))
min_val = lambda a, b: a if a < b else b
print("10. Min of 10 & 20:", min_val(10, 20))
2. Cube of 3: 27
3. Add 10 & 20: 30
4. Subtract 20 & 5: 15
5. Multiply 5 & 6: 30
6. Divide 20 & 4: 5.0
7. Is 10 Even?: True
8. Is 9 Odd?: True
9. Max of 10 & 20: 20
10. Min of 10 & 20: 10
12. Quick Revision Summary
Cheat Sheet Summary
- lambda args: expr -> Anonymous function creator.
- map(lambda, list) -> Transforms list items.
- filter(lambda, list) -> Filters list items by condition.
- sorted(list, key=lambda) -> Custom sorting.
- Floor Division 10 // 2 gives 5 (int), Floating Division 10 / 2 gives 5.0 (float).
Quick Revision (Short Notes)
- lambda = Chota nameless function single line ka.
- map() = Har element par operation apply karna.
- filter() = True/False ke basis par items select karna.
- sorted() = Custom key (jaise tuple marks) se sort karna.
- 10//2 integer quotient (5) deta hai, jabki 10/2 float output (5.0) deta hai.