What is the difference between map(), filter(), and reduce() in Python?
What is the difference between map(), filter(), and reduce() in Python?
What is the difference between map(), filter(), and reduce() in Python?
solveurit24@gmail.com Changed status to publish February 13, 2025
map(func, iterable): Appliesfuncto each item initerableand returns the results as an iterator.filter(func, iterable): Returns items fromiterablefor whichfuncreturnsTrue.reduce(func, iterable): Appliesfunccumulatively to the items ofiterableto produce a single result.
Example:
from functools import reduce
# map: square each number
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16]
# filter: keep even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
# reduce: sum all numbers
total = reduce(lambda x, y: x + y, numbers) # 10
solveurit24@gmail.com Changed status to publish February 13, 2025