Newby Coder header banner

Python Map Filter Reduce

Map Filter and Reduce are methods which allow to apply a function on the objects of a collection like list dict etc

These allow a programmer to write shorter code without needing to bother about loops

map and filter are built-in functions in Python, while reduce has to be imported

Python Map

Python map function is typically used to iterate through a collection(or iterable) and return a new object for each object of the collection, based on the function passed to the map function

For example it can be used on a list containing user data to get a list containing only the names of each user

Syntax of Python map() function

 map(func, *iterables) 
Where, func is the function to be applied for each element of the iterables

If there are multiple iterables, then func is passed an element from each iterable for each iteration in the order provided

Python map() example

Consider the following example which contains a list containing first and last names of users andderives a list with full names

userList = [{"firstName": "Arthur", "lastName": "Revokiv"}, {"firstName": "Teal", "lastName":"Cupo"}, {"firstName": "Nang", "lastName": "Zemo"}]
fullNames = []
for user in userList:
    fullNames.append(user["firstName"] + ' ' + user["lastName"])

print(fullNames)

Output

['Arthur Revokiv', 'Teal Cupo', 'Nang Zemo']

Same can be done by using map() function

userList = [{"firstName": "Arthur", "lastName": "Revokiv"}, {"firstName": "Teal", "lastName":"Cupo"}, {"firstName": "Nang", "lastName": "Zemo"}]
def fullName(user):
    return user["firstName"] + ' ' + user["lastName"]

fullNames = list(map(fullName, userList))
print(fullNames)

Output

['Arthur Revokiv', 'Teal Cupo', 'Nang Zemo']

Here, the map(fullName, userList) function iterates through userList and applies method fullName for each element

list() function is used to convert the map object return by map() function into a list


The method fullName() can be replaced with a lambda to further shorten the code

userList = [{"firstName": "Arthur", "lastName": "Revokiv"}, {"firstName": "Teal", "lastName":"Cupo"}, {"firstName": "Nang", "lastName": "Zemo"}]
fullNames = list(map(lambda x: x["firstName"] + ' ' + x["lastName"], userList))
print(fullNames)

Python map() with multiple iterables

In case of multiple iterables :

Following example uses map() function to iterate 2 lists and return a list with the max of corresponding elements (corresponding in terms of index)

numbers1 = [2, 23, 46, 242, 4534, 43]
numbers2 = [14, 325, 3, 515, 24, 43, 56, 36]
max=list(map(lambda x,y: x if x > y else y, numbers1, numbers2))
print(max)

Output

[14, 325, 46, 515, 4534, 43]

x if x > y else y is one-liner for

if x > y:
    return x
else:
    return y

Elements of the larger list for which no corresponding elements were found, were skipped

Python Filter

Python Filter function is used to apply a condition on an iterable to return an iterable containing the elements for which the condition evaluates to true

Syntax of Python filter() function

filter(func, iterable)

Similar to map() function filter function accepts a function as argument but requires the function to return a boolean value

Unlike map(), filter() only accepts one iterable

Example of Python filter() function

Following example filters a list of numbers to get numbers divisible by 3, 7 or 11

numbers = [13423, 14443, 3532, 131791, 3645311, 25974, 21532]
def is_divisible(n):
    if n % 3 == 0:
        return True
    if n % 7 == 0:
        return True
    if n % 11 == 0:
        return True

list2 = list(filter(is_divisible, numbers))
print(list2)

Output

[14443, 131791, 25974, 21532]

Following example uses filter() to return the elements of a list containing a specific substring

fn = ["pic1.jpg", "python.py", "bootstrap.js", "chart.jpg", "screenshot.jpeg"]
jpgList = list(filter(lambda x: ".jpg" in x, fn))
print(jpgList)

Output

['pic1.jpg', 'chart.jpg']

Python Reduce

reduce iterates through an iterable and applies a function (of two arguments) to consecutive elements of an iterable, optionally starting with an initial argument

In the first iteration, the function is passed the values of first and second elements (or the initial argument and first element, if initial is provided)

For consecutive iterations, it is passed the result of the previous iteration and the next element

Syntax of Python reduce() method

It has the following syntax:

reduce(func, iterable[, initial])

It has to be imported as from functools import reduce

Example of Python reduce() method

Following example finds the total and smallest number of a list using reduce()

numbers = [13423, 14443, 3532, 131791, 3645311, 25974, 21532]
def sum(x ,y):
    return x + y

total = reduce(sum, numbers)
min = reduce(lambda x,y: y if x > y else x, numbers)
print("Sum :", total)
print("Min :", min)

Output

Sum : 3856006
Min : 3532