Python map, filter and reduce
In Python, the map()
, filter()
, and reduce()
functions are built-in functions that are used to perform operations on lists and other iterable objects.
Map
map()
function applies a given function to all items of an input list and returns a new list with the modified items. The basic syntax of the map function is as follows:
1Syntax: 2map(function, iterable)
Here is an example of using the map()
function to square all the numbers in a list:
1Syntax: 2numbers = [1, 2, 3, 4, 5] 3squared_numbers = list(map(lambda x: x**2, numbers)) 4print(squared_numbers) # [1, 4, 9, 16, 25]
The map()
function applies a given function to all items of an input list.
Filter
filter()
function filters the items of an input list based on a given function and returns a new list with the items that pass the filter. The basic syntax of the filter function is as follows:
1Syntax: 2filter(function, iterable)
Here is an example of using the filter()
function to get even numbers from a list:
1numbers = [1, 2, 3, 4, 5] 2even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) 3print(even_numbers) # [2, 4]
filter()
function filters the items of an input list based on a given function.
Reduce
reduce()
function applies a given function cumulatively on the items of an input list and returns a single value. The basic syntax of the reduce function is as follows:
1syntax: 2reduce(function, iterable)
Here is an example of using the reduce()
function to find the product of all the numbers in a list:
1from functools import reduce 2numbers = [1, 2, 3, 4, 5] 3product = reduce(lambda x, y: x+y, numbers) 4print(product) # 15
reduce()
function applies a given function cumulatively on the items of an input list and returns a single value.