๐ฏ Lesson Objective
To learn anonymous functions with lambda, and functional programming tools like map, filter, and reduce for concise and efficient data processing.
๐งฉ 1. Lambda Functions
A lambda function is a small anonymous function defined with the lambda keyword.
Syntax:
lambda arguments: expression
โ Example 1: Square of a Number
square = lambda x: x**2
print(square(5))
Output:
25
โ Example 2: Sum of Two Numbers
add = lambda a, b: a + b
print(add(10, 15))
Output:
25
๐ 2. Map Function
map() applies a function to each element of an iterable.
Syntax:
map(function, iterable)
โ Example: Square a List of Numbers
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
print(squares)
Output:
[1, 4, 9, 16, 25]
๐งฐ 3. Filter Function
filter() returns elements of an iterable that satisfy a condition.
Syntax:
filter(function, iterable)
โ Example: Even Numbers from a List
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
Output:
[2, 4, 6]
๐งฑ 4. Reduce Function
reduce() applies a function cumulatively to the items of an iterable to reduce it to a single value.
Requires
functoolsmodule.
from functools import reduce
nums = [1, 2, 3, 4, 5]
sum_all = reduce(lambda x, y: x + y, nums)
print(sum_all)
Output:
15
โ Example 2: Product of Numbers
product = reduce(lambda x, y: x * y, nums)
print(product)
Output:
120
๐ 5. Combining Map, Filter, Reduce
โ Example: Sum of Squares of Even Numbers
from functools import reduce
nums = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, nums)
squares = map(lambda x: x**2, evens)
sum_squares = reduce(lambda x, y: x + y, squares)
print(sum_squares)
Output:
56
๐ 6. Real-Life Example โ Processing Grades
grades = [80, 90, 75, 88, 95]
# Increase each grade by 5
grades_inc = list(map(lambda x: x + 5, grades))
# Keep only grades >= 90
top_grades = list(filter(lambda x: x >= 90, grades_inc))
# Sum of top grades
total_top = reduce(lambda x, y: x + y, top_grades)
print("Grades +5:", grades_inc)
print("Top Grades:", top_grades)
print("Sum of Top Grades:", total_top)
Output:
Grades +5: [85, 95, 80, 93, 100]
Top Grades: [95, 93, 100]
Sum of Top Grades: 288

Leave a Reply