Lambda Functions


lambda function is a small anonymous function in Python.
It can take any number of arguments, but has only one expression.


🔹 Syntax

lambda arguments: expression

Example:

add = lambda a, b: a + b
print(add(5, 3))  # 8

🔹 Lambda vs Def

Feature lambda def
Named Optional Required
Use case One-liner function Multi-line logic
Return Implicit Can use return keyword

🔹 Lambda Inside Function

def multiplier(n):
    return lambda x: x * n

double = multiplier(2)
print(double(5))  # 10

🔹 Use with map()

nums = [1, 2, 3]
squared = list(map(lambda x: x**2, nums))
print(squared)  # [1, 4, 9]

🔹 Use with filter()

nums = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)  # [2, 4]

🔹 Use with sorted()

data = [(1, 'a'), (3, 'c'), (2, 'b')]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)  # [(1, 'a'), (2, 'b'), (3, 'c')]


Practice Questions

Q1. Write a Python program to create a lambda function that multiplies two numbers.

Q2. Write a Python program to create a lambda function that checks if a number is even.

Q3. Write a Python program to use a lambda function to return the cube of a number.

Q4. Write a Python program to use lambda with map() to double all values in a list.

Q5. Write a Python program to filter out numbers greater than 10 from a list using lambda and filter().

Q6. Write a Python program to sort a list of names by length using a lambda function.

Q7. Write a Python program to create a function that returns a lambda which triples a number.

Q8. Write a Python program to combine def and lambda to create dynamic multipliers, like make_multiplier(5)(2) → 10.

Q9. Write a Python program to use lambda with filter() to find multiples of 3 in a list.

Q10. Write a Python program to create a lambda function that takes 3 parameters and returns their sum.


Go Back Top