1 min read

Python Map, Filter, and Reduce

Python provides several functional programming tools that allow you to process data efficiently. Three of the most common are map(), filter(), and reduce().

map()

The map() function applies a given function to each item of an iterable (list, tuple, etc.) and returns a map object (which is an iterator).

Syntax

map(function, iterable)

Example

def square(n):
    return n * n

numbers = [1, 2, 3, 4]
result = map(square, numbers)
print(list(result)) # Output: [1, 4, 9, 16]

filter()

The filter() function filters elements from an iterable based on a function that returns True or False.

Syntax

filter(function, iterable)

Example

def check_even(n):
    return n % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
result = filter(check_even, numbers)
print(list(result)) # Output: [2, 4, 6]

reduce()

The reduce() function applies a rolling computation to sequential pairs of values in a list. It is defined in the functools module.

Example

from functools import reduce

numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, numbers)
print(result) # Output: 10

programming/python/python