Lecture 7 – Lambda, Map, Filter, Reduce (Functional Programming in Python)

Learn Python functional programming in Lecture 7. Understand lambda expressions, map(), filter(), and reduce() with easy examples, real Data Science use-cases, MCQs, and practice tasks for beginners.

What You Will Learn

By the end of this lecture, you will understand:

What lambda (anonymous functions) are
How to write lambda expressions
When to use lambda vs normal functions
How map() transforms data
How filter() extracts useful data
How reduce() combines data
Functional programming patterns
Real Data Science examples
MCQs + practice problems

1) What Is a Lambda Function?

A lambda is a small, anonymous function without a name.

Normal Function:
def square(x):
    return x * x
Lambda version:
square = lambda x: x * x

Both give the same result.

2) Basic Lambda Examples

Example 1 – Square a number
square = lambda x: x * x
print(square(6))
Example 2 – Add two numbers
add = lambda a, b: a + b
print(add(5, 3))
Example 3 – Even/odd check
is_even = lambda n: n % 2 == 0
print(is_even(10))
Example 4 – Get last character of a string
last_char = lambda text: text[-1]
print(last_char("Python"))

3) Lambda in Sorting

Example – Sort list of tuples by second value
data = [(1, 4), (3, 1), (2, 5)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)

Python Documentation

4) map() Function – Transform Each Item in a Collection

Syntax:
map(function, iterable)
Example 1 – Square all numbers
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)
Example 2 – Convert string numbers to integers
raw = ["10", "20", "30"]
clean = list(map(lambda x: int(x), raw))
print(clean)
Example 3 – Convert Celsius → Fahrenheit
temps = [0, 10, 25, 30]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, temps))
print(fahrenheit)

5) filter() Function – Keep Only True Items

Syntax:
filter(function, iterable)
Example 1 – Keep even numbers
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
Example 2 – Extract names starting with “A”
names = ["Ali", "Sara", "Ayesha", "Hamza"]
a_names = list(filter(lambda x: x.startswith("A"), names))
print(a_names)
Example 3 – Keep positive values
values = [-5, 0, 10, -2, 15]
positive = list(filter(lambda x: x > 0, values))
print(positive)

Lecture 6 – Functions

6) reduce() Function – Combine All Items into One

(Must import from functools)

Syntax:
from functools import reduce
reduce(function, iterable)
Example 1 – Sum all numbers
from functools import reduce

nums = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, nums)
print(total)
Example 2 – Multiply all numbers
product = reduce(lambda a, b: a * b, nums)
print(product)
Example 3 – Longest word in list
words = ["AI", "Python", "ElecturesAI"]
longest = reduce(lambda a, b: a if len(a) > len(b) else b, words)
print(longest)

7) Real Data Science Examples

Example 1 – Clean missing values
data = ["12", "15", "N/A", "20"]
clean = list(filter(lambda x: x != "N/A", data))
clean = list(map(lambda x: int(x), clean))
print(clean)
Example 2 – Normalize dataset values
nums = [10, 20, 30, 40]

normalized = list(map(lambda x: x / max(nums), nums))
print(normalized)
Example 3 – Remove outliers
values = [10, 12, 13, 500, 11, 14]

filtered = list(filter(lambda x: x < 100, values))
print(filtered)
Example 4 – Sum of squared values
from functools import reduce

nums = [2, 3, 4]

result = reduce(lambda a, b: a + b, map(lambda x: x*x, nums))
print(result)
Example 5 – Convert names to uppercase
names = ["talha", "ali", "sara"]
upper = list(map(lambda x: x.upper(), names))
print(upper)

Quiz – Test Your Understanding
Instruction: First read the question and choose your answer. Then scroll down to see the correct answer


Lambda functions are:

a) Named functions
b) Anonymous functions
c) Loops
d) Classes

Answer: b) Anonymous functions

map() is used to:

a) Filter items
b) Loop manually
c) Transform each item
d) Delete items

Answer: c) Transform each item

Which module contains reduce()?

a) math
b) numpy
c) functools
d) itertools

Answer: c) functools

What will this return?

list(filter(lambda x: x > 3, [1,2,3,4,5]))

Answer: [4, 5]

Next Lecture 8 – Modules & Packages


Practice Questions
Instruction for students: Read the question, open your Jupyter Notebook, and try to solve it yourself. After that, come back and check the answer.

Use map() to cube all numbers in a list.
nums = [1, 2, 3, 4]
cubes = list(map(lambda x: x**3, nums))
print(cubes)
Use filter() to keep only strings longer than 5 characters.
words = ["python", "ai", "data", "science"]
result = list(filter(lambda x: len(x) > 5, words))
print(result)
Use reduce() to find the maximum value in a list.
from functools import reduce

nums = [10, 55, 42, 99, 3]
max_val = reduce(lambda a, b: a if a > b else b, nums)
print(max_val)
Use lambda to check if a number is divisible by 3.
check = lambda x: x % 3 == 0
print(check(9))
Use map() + filter() together to:
Square numbers
Keep only results > 20Add Your Accordion Title
nums = [2, 3, 4, 5]

result = list(
    filter(lambda x: x > 20,
           map(lambda x: x*x, nums))
)

print(result)

Leave a Reply

Your email address will not be published. Required fields are marked *