⚡ What is a Lambda Function in Python?
A lambda function is a small anonymous function that
can accept any number of arguments but contains only one expression.
Lambda functions are useful when a short function is required temporarily,
especially with functions such as map(), filter(),
sorted(), and reduce().
The basic syntax is:
lambda arguments: expression.
1. Basic Lambda Function
Create a simple anonymous function that receives a number and returns
its square. Lambda is useful when the operation is short enough to
fit into a single expression.
Python
square = lambda number: number * number
result = square(8)
print("Square:", result)
Output:
Square: 64
Real-Time Example 1: Calculate Product Discount
Online shopping applications frequently calculate discounts.
A lambda function can perform a small pricing calculation without
creating a separate named function.
Python
discount_price = lambda price, discount: price - (price * discount / 100)
product_price = 2500
discount = 20
final_price = discount_price(product_price, discount)
print("Original Price: ₹", product_price)
print("Discount: ", discount, "%")
print("Final Price: ₹", final_price)
Output:
Original Price: ₹ 2500
Discount: 20 %
Final Price: ₹ 2000.0
Real-Time Example 2: Sorting Products by Price
E-commerce applications often sort products based on price.
The
key parameter of sorted() can use
a lambda function to tell Python which value should be used for sorting.
Python
products = [
{"name": "Laptop", "price": 65000},
{"name": "Mouse", "price": 1200},
{"name": "Keyboard", "price": 2500},
{"name": "Monitor", "price": 18000}
]
sorted_products = sorted(
products,
key=lambda product: product["price"]
)
for product in sorted_products:
print(product["name"], "→ ₹", product["price"])
Output:
Mouse → ₹ 1200
Keyboard → ₹ 2500
Monitor → ₹ 18000
Laptop → ₹ 65000
Real-Time Example 3: Filtering Active Users
Applications often need to display only active users.
A lambda function can be combined with
filter()
to select records that satisfy a condition.
Python
users = [
{"name": "Rahul", "active": True},
{"name": "Priya", "active": False},
{"name": "Amit", "active": True},
{"name": "Sneha", "active": False}
]
active_users = list(
filter(lambda user: user["active"], users)
)
print("Active Users:")
for user in active_users:
print(user["name"])
Output:
Active Users:
Rahul
Amit
Real-Time Example 4: Transforming Data with map()
The
map() function applies an operation to every item
in a collection. Lambda is commonly used when that operation is
short and does not need a separate function.
Python
prices = [1000, 1500, 2000, 2500]
gst_prices = list(
map(lambda price: price * 1.18, prices)
)
print("Prices including 18% GST:")
for price in gst_prices:
print("₹", price)
Output:
Prices including 18% GST:
₹ 1180.0
₹ 1770.0
₹ 2360.0
₹ 2950.0
Real-Time Example 5: Sorting Employees by Salary
HR systems frequently sort employee records according to salary.
A lambda function can directly select the salary field used by
sorted().
Python
employees = [
{"name": "Anita", "salary": 55000},
{"name": "Vikram", "salary": 72000},
{"name": "Rohan", "salary": 48000},
{"name": "Meera", "salary": 90000}
]
employees_by_salary = sorted(
employees,
key=lambda employee: employee["salary"],
reverse=True
)
for employee in employees_by_salary:
print(
employee["name"],
"→ ₹",
employee["salary"]
)
Output:
Meera → ₹ 90000
Vikram → ₹ 72000
Anita → ₹ 55000
Rohan → ₹ 48000
Real-Time Example 6: Find Even Numbers
Data-processing programs often need to select values based on a
condition. A lambda expression can be used with
filter()
to keep only even numbers.
Python
numbers = [10, 15, 22, 31, 40, 55, 64]
even_numbers = list(
filter(lambda number: number % 2 == 0, numbers)
)
print("Even Numbers:", even_numbers)
Output:
Even Numbers: [10, 22, 40, 64]
Real-Time Example 7: Convert Names to Uppercase
Data received from forms, files, or APIs may need formatting before
being displayed. Lambda with
map() can quickly transform
every name into uppercase.
Python
names = [
"rahul",
"priya",
"amit",
"sneha"
]
formatted_names = list(
map(lambda name: name.upper(), names)
)
print("Formatted Names:", formatted_names)
Output:
Formatted Names: ['RAHUL', 'PRIYA', 'AMIT', 'SNEHA']
Real-Time Example 8: Filter Products Above a Price
A shopping application may allow users to display products above
a selected budget. Lambda and
filter() provide a compact
way to implement this condition.
Python
products = [
{"name": "Phone", "price": 30000},
{"name": "Laptop", "price": 75000},
{"name": "Tablet", "price": 25000},
{"name": "Monitor", "price": 18000}
]
budget = 25000
expensive_products = list(
filter(lambda product: product["price"] > budget, products)
)
for product in expensive_products:
print(product["name"], "→ ₹", product["price"])
Output:
Phone → ₹ 30000
Laptop → ₹ 75000
Real-Time Example 9: Lambda with Multiple Arguments
Lambda functions can accept multiple arguments. This is useful
for small calculations such as calculating an employee's monthly
salary after adding a bonus.
Python
calculate_total_salary = lambda salary, bonus: salary + bonus
salary = 60000
bonus = 10000
total = calculate_total_salary(salary, bonus)
print("Base Salary: ₹", salary)
print("Bonus: ₹", bonus)
print("Total Salary: ₹", total)
Output:
Base Salary: ₹ 60000
Bonus: ₹ 10000
Total Salary: ₹ 70000
Real-Time Example 10: Lambda with sorted() and Multiple Fields
Real applications sometimes need to sort records using more than
one field. A lambda can return a tuple so Python can sort by
multiple fields.
Python
students = [
{"name": "Rahul", "department": "IT", "marks": 82},
{"name": "Priya", "department": "CS", "marks": 91},
{"name": "Amit", "department": "IT", "marks": 91},
{"name": "Sneha", "department": "CS", "marks": 82}
]
sorted_students = sorted(
students,
key=lambda student: (
student["department"],
-student["marks"]
)
)
for student in sorted_students:
print(
student["department"],
"→",
student["name"],
"→",
student["marks"]
)
Output:
CS → Priya → 91
CS → Sneha → 82
IT → Amit → 91
IT → Rahul → 82
Real-Time Example 11: Lambda for API/Data Transformation
API responses commonly contain lists of dictionaries. Lambda can
extract only the required field before sending the data to another
part of an application.
Python
api_response = [
{
"id": 101,
"name": "Laptop",
"category": "Electronics"
},
{
"id": 102,
"name": "Chair",
"category": "Furniture"
},
{
"id": 103,
"name": "Mobile",
"category": "Electronics"
}
]
product_names = list(
map(lambda item: item["name"], api_response)
)
print("Products received from API:")
for name in product_names:
print(name)
Output:
Products received from API:
Laptop
Chair
Mobile
Real-Time Example 12: Lambda with reduce()
The
reduce() function repeatedly combines values into
a single result. It is useful for operations such as calculating
totals from a collection of values.
Python
from functools import reduce
cart_prices = [500, 1200, 750, 300]
total = reduce(
lambda first, second: first + second,
cart_prices
)
print("Shopping Cart Total: ₹", total)
Output:
Shopping Cart Total: ₹ 2750
Summary of Python Lambda Functions
- Anonymous Function: A lambda creates a small function without giving it a traditional function name.
- Single Expression: Lambda functions contain one expression whose result is returned automatically.
-
map():
Use lambda with
map()to transform every item in a collection. -
filter():
Use lambda with
filter()to select items that satisfy a condition. -
sorted():
Use lambda with
sorted()to specify the field or calculation used for sorting. -
reduce():
Use lambda with
reduce()when multiple values need to be combined into one result. -
Best Use:
Lambda functions are most useful for short, simple operations.
For complex business logic, a normal
deffunction is generally easier to read and maintain.