๐ Phase 1: Programming Fundamentals
๐ Topic 9: Python Lambda Functions, map(), filter(), and reduce()
Welcome back! ๐
So far, you've learned Python basics, loops, functions, data structures, and list comprehensions. In this lesson, you'll learn functional programming concepts in Python using Lambda Functions, map(), filter(), and reduce().
These are widely used in Data Science for transforming, filtering, and processing large datasets efficiently.
๐น 1. What is a Lambda Function?
A Lambda Function is a small anonymous function that can have any number of arguments but only one expression.
Unlike normal functions, lambda functions don't require a name.
Syntax
lambda arguments: expressionExample
square = lambda x: x * x
print(square(5))
Output:
25This is equivalent to:
def square(x):
return x * x
๐น 2. Why Use Lambda Functions?
Lambda functions are useful when:
โ You need a simple function only once.
โ You want shorter, cleaner code.
โ You're using functions like map(), filter(), or sorted().
๐น 3. Lambda with Multiple Arguments
add = lambda a, b: a + b
print(add(10, 20))
Output:
30๐น 4. The map() Function
The map() function applies a function to every item in an iterable.
Syntax:
map(function, iterable)Example
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)
Output:
[1, 4, 9, 16, 25]๐น 5. Using map() with a Normal Function
def double(x):
return x * 2
numbers = [1, 2, 3, 4]
result = list(map(double, numbers))
print(result)
Output:
[2, 4, 6, 8]๐น 6. The filter() Function
The filter() function selects only those elements that satisfy a condition.
Syntax:
filter(function, iterable)Example
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Output:
[2, 4, 6]๐น 7. The reduce() Function
The reduce() function applies a function repeatedly to reduce an iterable to a single value.
It is available in the
functools module.from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(lambda a, b: a + b, numbers)
print(result)
Output:
10๐น 8. Difference Between map(), filter(), and reduce()
map(): Transforms every element in an iterable and returns a new iterable.
filter(): Keeps only elements that match a condition and returns a filtered iterable.
reduce(): Combines all elements into a single value.
๐น 9. Real-World Data Science Example
Suppose you have customer purchase amounts.
purchases = [1200, 450, 1800, 900, 2500]
high_value = list(filter(lambda x: x > 1000, purchases))
print(high_value)
Output:
[1200, 1800, 2500]Now calculate the total revenue.
from functools import reduce
total = reduce(lambda a, b: a + b, purchases)
print(total)
Output:
6850๐น 10. Combining map() and filter()
numbers = [1, 2, 3, 4, 5, 6]
result = list(
map(
lambda x: x * 10,
filter(lambda x: x % 2 == 0, numbers)
)
)
print(result)