Lambda Functions in Python
Lambda functions are small, one-line functions that do not require a name. They are useful when you want to create quick, simple functions without writing a full def block. Python developers commonly use lambda functions for data processing, filtering, mapping, and sorting.
What Is a Lambda Function?
A lambda function is an anonymous (nameless) function. It contains only one expression and automatically returns the result of that expression.
lambda arguments : expression
This means:
• Write lambda
• Provide the inputs
• Write a single expression that produces a result
Example 1: Basic Lambda Function
This lambda function doubles a number:
double = lambda x: x * 2
print(double(5))
Output: 10
Example 2: Lambda With Multiple Inputs
add = lambda a, b: a + b
print(add(10, 20))
Output: 30
When Should You Use Lambda?
Lambda functions are helpful when:
- You need a short, temporary function
- You want cleaner, shorter code
- You are working with map(), filter(), or sorted()
- You need to pass a function as an argument
Using Lambda With map()
The map() function applies the lambda to every element of a list.
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)
Output: [1, 4, 9, 16, 25]
Using Lambda With filter()
filter() keeps only the elements that satisfy the condition.
numbers = [10, 15, 20, 25, 30]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output: [10, 20, 30]
Using Lambda With sorted()
Lambda helps Python decide how sorting should happen.
students = [
("Rahul", 85),
("Anjali", 92),
("Kiran", 78)
]
sorted_list = sorted(students, key=lambda x: x[1])
print(sorted_list)
Output: [('Kiran', 78), ('Rahul', 85), ('Anjali', 92)]
Lambda vs Normal Function
| Normal Function | Lambda Function |
|---|---|
| Can have multiple lines | Only one line |
| Uses def | Uses lambda |
| Good for bigger logic | Good for small tasks |
Real-World Example: Discount Calculator
discount_price = lambda price, discount: price - (price * discount / 100)
print(discount_price(1000, 10))
Output: 900
📝 Practice Exercises
Exercise 1
Create a lambda function that adds 5 to a number.
Exercise 2
Use lambda + map() to convert a list of names to uppercase. Example list: ["sree", "kiran", "aarav"]
Exercise 3
Use lambda + filter() to return numbers greater than 50 from: [10, 55, 43, 90, 12, 75]
Exercise 4
Use lambda + sorted() to sort this list based on age: ("Ravi", 21), ("Karthik", 18), ("Meena", 25)
✅ Practice Answers
Answer 1
add_five = lambda x: x + 5
print(add_five(10))
Answer 2
names = ["sree", "kiran", "aarav"]
upper_names = list(map(lambda n: n.upper(), names))
print(upper_names)
Answer 3
numbers = [10, 55, 43, 90, 12, 75]
result = list(filter(lambda x: x > 50, numbers))
print(result)
Answer 4
people = [("Ravi", 21), ("Karthik", 18), ("Meena", 25)]
sorted_people = sorted(people, key=lambda x: x[1])
print(sorted_people)