⚡ What is a Lambda Function in Python?
A lambda function is a small anonymous (nameless) function defined using the lambda keyword.
Unlike standard functions defined with def, lambda functions can take any number of arguments but can only evaluate and return a single expression. They are frequently used as short-term inline functions passed into higher-order functions like map(), filter(), and sorted().
1. Basic Lambda Syntax & Comparison
Compare a standard multi-line function definition with a compact one-line lambda expression.
Python
# Standard function definition
def square_standard(x):
return x ** 2
# Lambda function definition [lambda arguments: expression]
square_lambda = lambda x: x ** 2
print("Standard Function Output:", square_standard(5))
print("Lambda Function Output:", square_lambda(5))
Output:
Standard Function Output: 25
Lambda Function Output: 25
Real-Time Example 1: Multiple Arguments in Lambda
Lambda functions can accept multiple arguments separated by commas.
Python
# Lambda to calculate rectangle area
calculate_area = lambda length, width: length * width
print("Calculated Area:", calculate_area(12, 5))
Output:
Calculated Area: 60
Real-Time Example 2: Sorting Complex Dictionaries with sorted()
Use a lambda expression as the
key parameter to sort a list of employee dictionaries by salary or age.
Python
employees = [
{"name": "Rahul", "salary": 45000},
{"name": "Priya", "salary": 75000},
{"name": "Amit", "salary": 60000}
]
# Sort employees by salary in ascending order using lambda
sorted_employees = sorted(employees, key=lambda emp: emp["salary"])
print("Sorted Employees by Salary:")
for e in sorted_employees:
print(f"- {e['name']}: ₹{e['salary']}")
Output:
Sorted Employees by Salary:
- Rahul: ₹45000
- Amit: ₹60000
- Priya: ₹75000
Real-Time Example 3: Filtering Lists with filter()
Filter numbers or items from a collection using
filter() combined with a lambda condition.
Python
scores = [45, 82, 39, 90, 67, 52]
# Filter passing scores (>= 50)
passing_scores = list(filter(lambda s: s >= 50, scores))
print("Original Scores:", scores)
print("Passing Scores (>= 50):", passing_scores)
Output:
Original Scores: [45, 82, 39, 90, 67, 52]
Passing Scores (>= 50): [82, 90, 67, 52]
Real-Time Example 4: Transforming Collections with map()
Apply a transformation operation to every item in a list using
map() and lambda.
Python
item_prices_inr = [450, 1200, 3500]
# Apply 5% GST tax increase using map and lambda
prices_with_gst = list(map(lambda p: round(p * 1.05, 2), item_prices_inr))
print("Prices in INR:", item_prices_inr)
print("Prices with 5% GST:", prices_with_gst)
Output:
Prices in INR: [450, 1200, 3500]
Prices with 5% GST: [472.5, 1260.0, 3675.0]
Real-Time Example 5: Conditional Logic (Ternary Operator in Lambda)
Incorporate if-else decision branching inside lambda functions using ternary syntax.
Python
# Lambda returning "Even" if number is divisible by 2 else "Odd"
check_even_odd = lambda n: "Even" if n % 2 == 0 else "Odd"
print("Number 14 is:", check_even_odd(14))
print("Number 7 is:", check_even_odd(7))
Output:
Number 14 is: Even
Number 7 is: Odd
Real-Time Example 6: Dynamic Multiplier Factory (Higher-Order Functions)
Return a custom lambda function dynamically from an outer factory function.
Python
def multiplier_factory(n):
return lambda x: x * n
double = multiplier_factory(2)
triple = multiplier_factory(3)
print("Double of 15:", double(15))
print("Triple of 15:", triple(15))
Output:
Double of 15: 30
Triple of 15: 45
Real-Time Example 7: Sorting Tuples by Specific Index
Sort a list of coordinate or database tuples based on specific column positions.
Python
# List of tuples: (ItemID, Price)
inventory = [(101, 1200), (102, 450), (103, 850)]
# Sort by price (index 1) in descending order
sorted_inventory = sorted(inventory, key=lambda item: item[1], reverse=True)
print("Inventory Sorted by Price (High to Low):", sorted_inventory)
Output:
Inventory Sorted by Price (High to Low): [(101, 1200), (103, 850), (102, 450)]
Real-Time Example 8: Event Handling Callback Simulation
Pass anonymous lambda callbacks to event dispatcher functions for UI or log actions.
Python
def trigger_event(event_name, callback):
print(f"Triggering event: {event_name}")
callback()
# Passing an inline lambda function as a callback
trigger_event("ButtonClick", lambda: print("Action: User submitted login form!"))
Output:
Triggering event: ButtonClick
Action: User submitted login form!
Real-Time Example 9: Custom Key Sorting for Strings (by Length)
Sort a list of words or file names by string length using a lambda key.
Python
words = ["Python", "AI", "Development", "Data"]
# Sort words by length shortest to longest
sorted_words = sorted(words, key=lambda w: len(w))
print("Words Sorted by Length:", sorted_words)
Output:
Words Sorted by Length: ['AI', 'Data', 'Python', 'Development']