What is the difference between map(), filter(), and reduce() in Python?

95 views

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
0
  • map(func, iterable): Applies func to each item in iterable and returns the results as an iterator.
  • filter(func, iterable): Returns items from iterable for which func returns True.
  • reduce(func, iterable): Applies func cumulatively to the items of iterable to 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
0