1. Home
  2. Docs
  3. Python 201
  4. Map, Filter and Reduce

Map, Filter and Reduce

In previous lessons you have learnt, List comprehensions.

In this lesson you learn about map(), filter() and reduce() built-in functions.

 
In below examples, you will see some lambda expression,
 
if are not sure what are lambda expression, check lambda functions.

 

map()

 
map() is built-in function, comes along with standard installation.
  

map(function, sequence)

  
It takes two arguments, a function and a sequence.
 
Sequence can be a list, tuple, or a string or any other sequence.

map() applies the function to all elements of a sequence.

It returns a new list of values after applying the function.

Let’s say we want list of squares of a given list.

[1,2,3,4,5,6,7,8,9,10]

  
Ex 1:
 

a = [1,2,3,4,5,6,7,8,9,10]

def square(x):
    return x * x

squares = map(square, a)

output:

squares

output:

<map at 0x172bd39fe80>


  
the map() function returns a map() object, which is generator object.

we can access the elements, either by next() built in method or

by iterating through map object.
 

for i in squares:

    print(i, end =" ")

output:

1 4 9 16 25 36 49 64 81 100 

  
Notice squares() function is applied to each element of list.

We can achieve this by list
comprehension
also, but map() more

efficient than list comprehensions.

Remember our song example from previous lesson,

getting length of, each song name by using list comprehension.

That can be achieved easily by using,

len() built in function and passing list to map() function.

 

using built-in function in map()

Ex 2:
  

songs = ['Stairway to Heaven','Whole Lotta Love','Black Dog','Rock and Roll']

len_songs = map(len,songs)


len_songs

output:

<map at 0x172bd3b8cf8>

  
returns a map object, for display purpose, we can convert it to list

and print.

len_songs = list(len_songs)

len_songs

output:

[18, 16, 9, 13]

  

Using conditional lambda in map() function

 
Ex 3:
 
Check the element is even in a given list.
  

a = [1,2,3,4,5,6,7,8,9,10]

even = lambda x: True if x %2 == 0 else False 

evens = list(map(even, a))

evens

output:

[False, True, False, True, False, True, False, True, False, True]

  

Using multiple sequences in map()

 
Ex 3:
 
Given two lists add each element.
  

a = [1,2,3]

b = [4,5,6]

add_list = list(map(lambda x,y: x+y, a,b))

add_list

output:

[5, 7, 9]    # 1 + 4, 2 + 5, 3 + 6

  
In this example, lambda x,y: x+y, is function part,

and a,b is sequence part of map() function.

x gets value from a, and y gets value from b
 

Ex 4:
 
Add elements of 3 lists.
  

a = [1,2,3]

b = [4,5,6]

c = [7,8,9]

add_list = list(map(lambda x,y,z: x+y+z, a,b,c))

add_list

output:

[12, 15, 18]

  

as in previous example x, y, z are each element of a,b,c respectively.

We can extended to any number of sequences,
 
but code looks and complicated and readability suffers.

  

Now we look at another useful function filter()
 

filter()

 

syntax:
  

filter(function or None, iterable)

  
filter() function filters out all elements of an iterable,
 
for which function returns True. If function is None,

returns all items that are true.

filter requires both arguments.

Let’s see some examples:
 
Ex 1:
  

a = [1,2,3,0,5,{},7,8,9,10,""]

filtered = filter(None,a)

filtered


output:

<filter at 0x172bd4d2b00>

  
Returns a filter object, with applied filter condition.

 
for display purpose, we can construct list from filter object.
  

filtered = list(filter(None,a))

filterd

output:

[1, 2, 3, 5, 7, 8, 9, 10]

  
Notice here we have not provided any filter function,

and the list contains, some None equivalents, 0, {} and “”

filter applies truthiness check on all elements, and omits which are False.
 

Using a filter condition, for filter function

 
Ex 2:
 
from given list return values higher than 5.
  

a = [1,2,3,4,5,6,7,8,9,10]

def more_than_five(x):

    if x > 5:

        return True

    else:

        return False
    
    
higher_values = list(filter(more_than_five, a))

higher_values

output:

[6, 7, 8, 9, 10]

  

Here more_than_five() returns True or False based on x value.

It’s act as filtering criteria.

This function needs to return a Boolean value.

more_than_five() is applied to every element of list.

if the function returns True for an element, it will be included in the result.

All other elements are filtered out.

 

Using map() and filter() in combination

 
From a given list, get squares of evens.

 

using map, filter and lambda functions together

  

a = [1,2,3,4,5,6,7,8,9,10]

even_squares = list(map(lambda i : i**2, filter(lambda i :i %2 ==0,a)))

print(alt_squares)


output:

[4, 16, 36, 64, 100]

  
At first it may look complicated, but its not.
 
let’s break it down,
 
lambda i : i**2 => returns squares of i

lambda i :i %2 == 0 => returns True of only even numbers.

filter takes two arguments

filter(lambda i :i %2 == 0, a) => function and a sequence

this results a filter object which generated even numbers.

in this case object that generates 2,4,6,8,10, lets its seq

seq = 2,4,6,8,10

map(lambda i : i**2, seq)

and the result is map object with sequence of squares of evens

which is converted to list() for display purpose.

map() and filter() are generally used with lambda functions,

As its not necessary to have a entire function for a quick job.

Now let’s move on to another powerful function reduce()

Note reduce() function is moved to functools module.

to use reduce() you have to import functools module.

importing reduce function from functools.
  

from functools import reduce


 
the documentation of reduce is very clear,

we can get it by using help() on reduce.
  

help(reduce)

output:


reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,

    from left to right, so as to reduce the sequence to a single value.

    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates

    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items

    of the sequence in the calculation, and serves as a default when the

    sequence is empty.

 
 

Let’s look at some example
 
Ex 1:
 

Sum of all elements of a list.

  

a =[1,2,3,4]

reduce(lambda x,y: x+y,a)

output:

10

  
here reduce() applies lambda function, cumulatively to each item of list.
 
result is ((((1+2))+3)+5) which results to 10,

You may wonder we can get the same result by using sum(a).

Actually the example shown here is very rudimentary,

perhaps of no practical use.

But it helps in understanding how reduce() works.
 
Let’s consider another simple example
 
Ex 2:
 
Maximum value in a list.
  

a =[11,2,13,41,34,30]

max_value = lambda x,y: x if (x > y) else y

reduce(max_value, a)

output:

41

  
Ex 3:
 
Get product of all list elements
  

a =[1,2,3,4,5,6]

list_product = lambda x, y: x * y

reduce(list_product, a)

output:

720

  
The result 720 is obtained like this, (((((1*2)*3)*4)*5)*6)

Reduce applied lambda function cumulatively on each item of a list.