DEV Community

Cover image for Python map(), filter() and reduce()
Max
Max

Posted on

Python map(), filter() and reduce()

map(), filter(), and reduce() are built-in Python functions that are used to perform data manipulation on iteratable of data such as lists, tuples, and sets.

Lambda function

Python lambda is a anonymous function, declared using single line expression. It can be passed as arguments in function call. Using this with map, filter and reduce makes it easier to write the expression in a single statement and easier to understand.

Map function

Syntax

map(function, iterator)
Enter fullscreen mode Exit fullscreen mode

The map() function will send the each values from the iterator to the function, it will return the processed value. map will returns an iterator containing the results of the processed values.

Example:

# square the values of a list using map()
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda i: i ** 2, numbers))
print(squared_numbers) 


# Output: [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

filter function

Syntax

filter(function, iterator)
Enter fullscreen mode Exit fullscreen mode

The filter() function is similar to map but with one difference, it will return the new iterator based on the function return value. It returns an iterator containing the elements from a sequence for which a given function returns True.

Example:

# filter even numbers from a list using filter()
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda i: i % 2 == 0, numbers))
print(even_numbers)


# Output: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

reduce function

Syntax

reduce(function, iterator)
Enter fullscreen mode Exit fullscreen mode

The reduce() function will take first two values from the iterator sequence, pass it as a argument to the function, then it will take the return value from the function and pass the value along with the next value from iterator as a argument to the function, this will continue till the end of the sequence list. Finally will return a single value.

Example:

# calculate the product of a list of numbers using reduce()
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
product = reduce(lambda i, j: i * j, numbers)
print(product) 


# Output: 3628800
Enter fullscreen mode Exit fullscreen mode

Top comments (0)