Lambda functions are small anonymous functions in Python. They are useful when you need a simple function for a short period of time. In this practice set, you’ll learn how to create lambda functions, pass arguments, use them with built-in functions, and solve beginner-friendly Python programs. Python lambda functions practice questions with solutions help to understand this concepts.
1. Python Program to Create a Simple Lambda Function
Problem Statement
Write a Python lambda function to add 10 to a given number.
Python Solution
add_ten = lambda number: number + 10
print(add_ten(15))
Sample Output
25
Explanation
A lambda function is created using the lambda keyword and returns the result automatically.
Concepts Covered
- lambda keyword
- Anonymous Function
2. Python Program to Add Two Numbers Using Lambda
Problem Statement
Write a Python lambda function to add two numbers.
Python Solution
add = lambda a, b: a + b
print(add(20, 15))
Sample Output
35
Explanation
Lambda functions can accept multiple arguments just like normal functions.
Concepts Covered
- Lambda Arguments
3. Python Program to Find the Square of a Number Using Lambda
Problem Statement
Write a Python lambda function to calculate the square of a number.
Python Solution
square = lambda number: number ** 2
print(square(9))
Sample Output
81
Explanation
The lambda function returns the square of the given number.
Concepts Covered
- Exponent Operator
- Lambda Function
4. Python Program to Find the Maximum of Two Numbers Using Lambda
Problem Statement
Write a Python lambda function to return the larger of two numbers.
Python Solution
maximum = lambda a, b: a if a > b else b
print(maximum(25, 40))
Sample Output
40
Explanation
The conditional expression selects the greater value.
Concepts Covered
- Conditional Expression
- Lambda Function
5. Python Program to Sort a List of Numbers Using Lambda
Problem Statement
Write a Python program to sort a list in ascending order using a lambda function.
Python Solution
numbers = [45, 12, 78, 23, 9]
numbers.sort(key=lambda number: number)
print(numbers)
Sample Output
[9, 12, 23, 45, 78]
Explanation
The key parameter accepts a lambda function that defines the sorting rule.
Concepts Covered
- sort()
- key
- lambda
6. Python Program to Sort a List of Tuples Using Lambda
Problem Statement
Write a Python program to sort students by age.
Python Solution
students = [
("Amit", 22),
("Rahul", 19),
("Neha", 21)
]
students.sort(key=lambda student: student[1])
print(students)
Sample Output
[('Rahul', 19), ('Neha', 21), ('Amit', 22)]
Explanation
The lambda function uses the second value (age) as the sorting key.
Concepts Covered
- List of Tuples
- Lambda Sorting
7. Python Program to Use Lambda with map()
Problem Statement
Write a Python program to double every number in a list using map() and a lambda function.
Python Solution
numbers = [2, 4, 6, 8]
result = list(map(lambda number: number * 2, numbers))
print(result)
Sample Output
[4, 8, 12, 16]
Explanation
The map() function applies the lambda function to every element.
Concepts Covered
- map()
- Lambda Function
8. Python Program to Use Lambda with filter()
Problem Statement
Write a Python program to filter even numbers from a list using filter() and a lambda function.
Python Solution
numbers = [10, 15, 20, 25, 30, 35]
result = list(filter(lambda number: number % 2 == 0, numbers))
print(result)
Sample Output
[10, 20, 30]
Explanation
The filter() function keeps only the elements that satisfy the condition.
Concepts Covered
- filter()
- Lambda Function
9. Python Program to Use Lambda with sorted()
Problem Statement
Write a Python program to sort words based on their length.
Python Solution
words = ["Python", "AI", "Programming", "Code"]
result = sorted(words, key=lambda word: len(word))
print(result)
Sample Output
['AI', 'Code', 'Python', 'Programming']
Explanation
The sorted() function uses the lambda function to compare word lengths.
Concepts Covered
- sorted()
- len()
- Lambda Function
10. Python Program to Find the Cube of a Number Using Lambda
Problem Statement
Write a Python lambda function to calculate the cube of a number.
Python Solution
cube = lambda number: number ** 3
print(cube(5))
Sample Output
125
Explanation
The lambda function returns the cube of the given number using the exponent operator.
Concepts Covered
- Lambda Function
- Exponent Operator
11. Python Program to Sort a List of Dictionaries by Salary Using Lambda
Problem Statement
Write a Python program to sort a list of employee dictionaries in descending order based on salary using a lambda function.
Python Solution
employees = [
{"Name": "Rahul", "Salary": 45000},
{"Name": "Priya", "Salary": 62000},
{"Name": "Aman", "Salary": 51000},
{"Name": "Neha", "Salary": 70000}
]
employees.sort(
key=lambda employee: employee["Salary"],
reverse=True
)
print("Employees Sorted by Salary:\n")
for employee in employees:
print(employee)
Sample Output
Employees Sorted by Salary:
{'Name': 'Neha', 'Salary': 70000}
{'Name': 'Priya', 'Salary': 62000}
{'Name': 'Aman', 'Salary': 51000}
{'Name': 'Rahul', 'Salary': 45000}
Explanation
The lambda function extracts the "Salary" value from each dictionary, allowing the sort() method to arrange employees in descending order.
Concepts Covered
- Lambda Functions
- sort()
- Dictionary Sorting
- Lists
12. Python Program to Filter Prime Numbers Using Lambda and filter()
Problem Statement
Write a Python program to filter prime numbers from a list using a lambda function with the filter() function.
Python Solution
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17]
is_prime = lambda n: (
n > 1 and all(n % i != 0 for i in range(2, int(n ** 0.5) + 1))
)
prime_numbers = list(filter(is_prime, numbers))
print("Prime Numbers:")
print(prime_numbers)
Sample Output
Prime Numbers:
[2, 3, 5, 7, 11, 13, 17]
Explanation
The lambda function checks whether a number is prime, and filter() keeps only the numbers that satisfy the condition.
Concepts Covered
- Lambda Functions
- filter()
- Prime Numbers
- all()
13. Python Program to Calculate the Product of List Elements Using Lambda and reduce()
Problem Statement
Write a Python program to calculate the product of all numbers in a list using a lambda function and the reduce() function.
Python Solution
from functools import reduce
numbers = [2, 3, 4, 5]
product = reduce(
lambda x, y: x * y,
numbers
)
print("Product =", product)
Sample Output
Product = 120
Explanation
The reduce() function repeatedly applies the lambda function to combine all elements into a single product.
Concepts Covered
- Lambda Functions
- reduce()
- functools Module
- Multiplication
14. Python Program to Sort Strings by Their Length Using Lambda
Problem Statement
Write a Python program to sort a list of strings based on their length using a lambda function.
Python Solution
languages = [
"Python",
"C",
"Java",
"JavaScript",
"SQL",
"Go"
]
sorted_languages = sorted(
languages,
key=lambda language: len(language)
)
print("Sorted List:")
print(sorted_languages)
Sample Output
Sorted List:
['C', 'Go', 'SQL', 'Java', 'Python', 'JavaScript']
Explanation
The lambda function returns the length of each string, allowing the sorted() function to arrange the list by string length.
Concepts Covered
- Lambda Functions
- sorted()
- len()
- String Sorting
15. Python Program to Find Students Scoring More Than 80 Marks Using Lambda
Problem Statement
Write a Python program to filter students who scored more than 80 marks using a lambda function.
Python Solution
students = {
"Rahul": 76,
"Priya": 92,
"Aman": 81,
"Neha": 88,
"Rohit": 65
}
top_students = dict(
filter(
lambda student: student[1] > 80,
students.items()
)
)
print("Students Scoring More Than 80 Marks:")
print(top_students)
Sample Output
Students Scoring More Than 80 Marks:
{'Priya': 92, 'Aman': 81, 'Neha': 88}
Explanation
The items() method converts the dictionary into key-value pairs. The lambda function filters only those students whose marks are greater than 80, and the filtered result is converted back into a dictionary.
Concepts Covered
- Lambda Functions
- filter()
- Dictionary
- items()
- Conditional Filtering
16. Python Program to Find the Student with the Highest Average Marks Using Lambda
Problem Statement
Write a Python program to find the student with the highest average marks from a dictionary containing subject-wise marks using a lambda function.
Python Solution
students = {
"Rahul": [85, 90, 88],
"Priya": [95, 96, 94],
"Aman": [78, 82, 80],
"Neha": [91, 89, 93]
}
top_student = max(
students.items(),
key=lambda student: sum(student[1]) / len(student[1])
)
average = sum(top_student[1]) / len(top_student[1])
print("Top Student:", top_student[0])
print("Average Marks:", round(average, 2))
Sample Output
Top Student: Priya
Average Marks: 95.0
Explanation
The lambda function calculates the average marks for each student. The max() function returns the student with the highest average score.
Concepts Covered
- Lambda Functions
- max()
- Dictionary
- Average Calculation
17. Python Program to Remove Duplicate Strings Using Lambda
Problem Statement
Write a Python program to remove duplicate strings from a list while preserving the original order using a lambda function.
Python Solution
words = [
"Python",
"Java",
"Python",
"SQL",
"Java",
"C++",
"Python"
]
remove_duplicates = lambda data: list(dict.fromkeys(data))
result = remove_duplicates(words)
print("Unique Words:")
print(result)
Sample Output
Unique Words:
['Python', 'Java', 'SQL', 'C++']
Explanation
The lambda function uses dict.fromkeys() to eliminate duplicate values while maintaining the insertion order.
Concepts Covered
- Lambda Functions
- dict.fromkeys()
- Lists
- Duplicate Removal
18. Python Program to Sort Tuples by Multiple Fields Using Lambda
Problem Statement
Write a Python program to sort employee records first by department and then by salary using a lambda function.
Python Solution
employees = [
("Rahul", "HR", 45000),
("Priya", "IT", 65000),
("Aman", "IT", 50000),
("Neha", "HR", 70000),
("Rohit", "Sales", 42000)
]
sorted_data = sorted(
employees,
key=lambda employee: (employee[1], employee[2])
)
print("Sorted Employee Records:\n")
for employee in sorted_data:
print(employee)
Sample Output
Sorted Employee Records:
('Rahul', 'HR', 45000)
('Neha', 'HR', 70000)
('Aman', 'IT', 50000)
('Priya', 'IT', 65000)
('Rohit', 'Sales', 42000)
Explanation
The lambda function returns a tuple containing the department and salary. Python sorts records by the first field and, if equal, by the second field.
Concepts Covered
- Lambda Functions
- Tuple Sorting
- Multiple Sorting Keys
- sorted()
19. Python Program to Find the Longest String Using Lambda
Problem Statement
Write a Python program to find the longest string in a list using a lambda function.
Python Solution
languages = [
"Python",
"Java",
"JavaScript",
"SQL",
"C++",
"TypeScript"
]
longest = max(
languages,
key=lambda language: len(language)
)
print("Longest String:", longest)
Sample Output
Longest String: TypeScript
Explanation
The lambda function returns the length of each string, allowing max() to identify the longest string.
Concepts Covered
- Lambda Functions
- max()
- len()
- String Processing
20. Python Program to Create a Price Calculator Using Lambda and map()
Problem Statement
Write a Python program to increase the price of every product by 18% GST using a lambda function and the map() function.
Python Solution
prices = [500, 1200, 2500, 800, 1500]
final_prices = list(
map(
lambda price: round(price * 1.18, 2),
prices
)
)
print("Prices After GST:")
print(final_prices)
Sample Output
Prices After GST:
[590.0, 1416.0, 2950.0, 944.0, 1770.0]
Explanation
The lambda function applies an 18% GST to each price. The map() function processes every element in the list and returns the updated prices.
Concepts Covered
- Lambda Functions
- map()
- Arithmetic Operations
- List Processing
21. Python Program to Find the Second Highest Salary Using Lambda
Problem Statement
Write a Python program to find the employee with the second highest salary from a list of dictionaries using a lambda function.
Python Solution
employees = [
{"Name": "Rahul", "Salary": 45000},
{"Name": "Priya", "Salary": 72000},
{"Name": "Aman", "Salary": 58000},
{"Name": "Neha", "Salary": 81000},
{"Name": "Rohit", "Salary": 65000}
]
sorted_employees = sorted(
employees,
key=lambda employee: employee["Salary"],
reverse=True
)
second_highest = sorted_employees[1]
print("Employee:", second_highest["Name"])
print("Salary:", second_highest["Salary"])
Sample Output
Employee: Priya
Salary: 72000
Explanation
The lambda function sorts employees by salary in descending order. The second element in the sorted list represents the employee with the second highest salary.
Concepts Covered
- Lambda Functions
- sorted()
- Dictionary
- Real-world Employee Data
22. Python Program to Group Words by Their First Letter Using Lambda
Problem Statement
Write a Python program to group words according to their first letter using a lambda function.
Python Solution
from itertools import groupby
words = [
"Apple",
"Ant",
"Banana",
"Ball",
"Cat",
"Car"
]
words.sort(key=lambda word: word[0])
groups = {
key: list(group)
for key, group in groupby(words, key=lambda word: word[0])
}
print(groups)
Sample Output
{
'A': ['Apple', 'Ant'],
'B': ['Ball', 'Banana'],
'C': ['Car', 'Cat']
}
Explanation
The list is first sorted by the initial letter. The groupby() function then groups consecutive words with the same starting character.
Concepts Covered
- Lambda Functions
- itertools.groupby()
- Dictionary Comprehension
- String Processing
23. Python Program to Find the Most Expensive Product Using Lambda
Problem Statement
Write a Python program to find the most expensive product from a nested dictionary using a lambda function.
Python Solution
products = {
"Laptop": {"Price": 65000},
"Mobile": {"Price": 30000},
"Monitor": {"Price": 18000},
"Keyboard": {"Price": 2500}
}
expensive = max(
products.items(),
key=lambda product: product[1]["Price"]
)
print("Most Expensive Product:", expensive[0])
print("Price:", expensive[1]["Price"])
Sample Output
Most Expensive Product: Laptop
Price: 65000
Explanation
The lambda function extracts the price from each nested dictionary, allowing max() to identify the product with the highest price.
Concepts Covered
- Lambda Functions
- Nested Dictionary
- max()
- Real-world Product Data
24. Python Program to Sort Students by Grade and Name Using Lambda
Problem Statement
Write a Python program to sort student records first by grade (descending) and then alphabetically by name using a lambda function.
Python Solution
students = [
{"Name": "Rahul", "Grade": 85},
{"Name": "Priya", "Grade": 92},
{"Name": "Aman", "Grade": 92},
{"Name": "Neha", "Grade": 78},
{"Name": "Rohit", "Grade": 85}
]
sorted_students = sorted(
students,
key=lambda student: (-student["Grade"], student["Name"])
)
print("Sorted Student Records:\n")
for student in sorted_students:
print(student)
Sample Output
Sorted Student Records:
{'Name': 'Aman', 'Grade': 92}
{'Name': 'Priya', 'Grade': 92}
{'Name': 'Rahul', 'Grade': 85}
{'Name': 'Rohit', 'Grade': 85}
{'Name': 'Neha', 'Grade': 78}
Explanation
The lambda function returns a tuple where the grade is negated to achieve descending order, while names are sorted alphabetically when grades are equal.
Concepts Covered
- Lambda Functions
- Multiple Sorting Keys
- sorted()
- Dictionary Sorting
25. Python Program to Build a Sales Report Using Lambda
Problem Statement
Write a Python program to calculate the total sales amount for each order using a lambda function and display the results.
Python Solution
orders = [
{"Product": "Laptop", "Price": 55000, "Quantity": 2},
{"Product": "Mouse", "Price": 800, "Quantity": 5},
{"Product": "Keyboard", "Price": 1500, "Quantity": 3},
{"Product": "Monitor", "Price": 18000, "Quantity": 2}
]
totals = list(
map(
lambda order: {
"Product": order["Product"],
"Total": order["Price"] * order["Quantity"]
},
orders
)
)
print("Sales Report:\n")
for item in totals:
print(item)
Sample Output
Sales Report:
{'Product': 'Laptop', 'Total': 110000}
{'Product': 'Mouse', 'Total': 4000}
{'Product': 'Keyboard', 'Total': 4500}
{'Product': 'Monitor', 'Total': 36000}
Explanation
The map() function applies a lambda expression to each order. The lambda calculates the total sales amount by multiplying the product price by its quantity and returns a new dictionary containing the product name and total amount.
Concepts Covered
- Lambda Functions
- map()
- Nested Dictionary
- Real-world Sales Report
- Functional Programming
Frequently Asked Questions (FAQs)
1. What is a lambda function in Python?
A lambda function is a small anonymous (unnamed) function that can have any number of arguments but only one expression. It is commonly used for short operations where creating a full function using def is unnecessary.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x ** 2
print(square(6))
Output
36
Concepts Covered
- Lambda Function
- Anonymous Function
- Expression
2. What is the difference between a lambda function and a normal function?
| Lambda Function | Normal Function |
|---|---|
| Anonymous function | Named function |
Uses lambda keyword | Uses def keyword |
| Single expression only | Multiple statements allowed |
| Automatically returns the result | Uses the return statement |
| Best for short operations | Best for complex logic |
Example:
# Lambda Function
multiply = lambda a, b: a * b
# Normal Function
def multiply_numbers(a, b):
return a * b
print(multiply(5, 4))
print(multiply_numbers(5, 4))
3. Can a lambda function have multiple arguments?
Yes. A lambda function can accept any number of arguments, but it can contain only one expression.
Example:
average = lambda a, b, c: (a + b + c) / 3
print(average(80, 90, 100))
Output
90.0
4. Why are lambda functions called anonymous functions?
Lambda functions are called anonymous because they do not require a function name. They are often created and used immediately without being stored in a variable.
Example:
print((lambda x: x + 10)(20))
Output
30
5. Where are lambda functions commonly used?
Lambda functions are widely used with built-in Python functions such as:
map()filter()reduce()sorted()max()min()
They are also frequently used in data analysis, automation, machine learning, and web development.
6. Can a lambda function contain loops or multiple statements?
No. Lambda functions can contain only a single expression. They cannot include loops, multiple statements, assignments, or control structures like for, while, or try.
For complex logic, use a normal function.
Incorrect Example
# Not Allowed
lambda x:
if x > 10:
return x
Correct Example
check = lambda x: "Greater" if x > 10 else "Smaller"
print(check(15))
7. What is the difference between map() and filter() with lambda?
map()transforms every element in an iterable.filter()selects only the elements that satisfy a condition.
Example
numbers = [1, 2, 3, 4, 5]
square = list(map(lambda x: x ** 2, numbers))
even = list(filter(lambda x: x % 2 == 0, numbers))
print(square)
print(even)
Output
[1, 4, 9, 16, 25]
[2, 4]
8. What is reduce() in Python, and how does it work with lambda?
The reduce() function applies a lambda function cumulatively to the elements of an iterable, reducing them to a single value.
It is available in the functools module.
Example
from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(
lambda x, y: x + y,
numbers
)
print(result)
Output
10
9. Are lambda functions faster than normal functions?
No. Lambda functions are not inherently faster than functions created with def. Both are compiled similarly by Python.
The main advantage of lambda functions is concise syntax and improved readability for short, one-time operations.
Choose:
- Lambda for simple expressions.
- Normal functions for reusable or complex logic.
10. Why are lambda functions important for Python interviews and real-world projects?
Lambda functions are frequently asked about in Python interviews because they demonstrate your understanding of functional programming and Python’s built-in higher-order functions.
Common interview topics include:
- Lambda expressions
map()filter()reduce()- Sorting using lambda
- Anonymous functions
- Functional programming concepts
- Data transformation
- Data filtering
- Real-world data processing
Lambda functions are extensively used in Data Science, Machine Learning, Artificial Intelligence, Automation, Pandas, NumPy, ETL pipelines, Backend Development, and Web Applications. Learning them helps you write cleaner, more concise, and more Pythonic code while improving your problem-solving skills for coding interviews and production-level projects.
Chapter Summary
After completing this chapter, you have learned:
- Lambda functions
- Anonymous functions
- Lambda with arguments
- Conditional expressions
- Lambda with
sort() - Lambda with
sorted() - Lambda with
map() - Lambda with
filter() - Real-world sorting using lambda
- Writing concise Python functions
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
