map(), zip(), reduce(), and filter() functions in Python

05 min read

The t=map(func, s) function applies the func to each of the elements in s and returns a new list, t. Each element of t is t[i] = func(s[i]). The function given to map()should only require one argument. For example, 

a = [1, 2,3,4,5,6]
def face(x):
     return 3*x
b=map(face,a)       #  b=[3, 6, 9,12, 15, 18]

Alternatively, using Lambda function, we can write as:

b= map(lambda x:3*x,a)      #  b=[3, 6, 9,12, 15, 18]

As an alternative to map(), a list of tuples can also becreated using the zip(s1, s2,...sn) function. zip() takes a collection of sequences and returns a new list, t, in which each element of t is t[i] = (s1[i], s2[i],...sn[i]). Unlike map(), zip() truncates the length of t to the shortest sequence in s1, s2,..sn. Consider an example, 

d= [1, 2, 3, 4, 5]
e= [10, 11, 12]
f= zip(d,e)       # f=[(1,10), (2,11), (3,12)]
g= map(None, d,e)

The reduce( func, s) function collects information from a sequence and returns a single value (for example, a sum, maximum value, and so on). reduce() works by applying the function func to the first two elements of s. This value is then combined with the fourth element, and so forth until the end of the sequence. The function func must accept two arguments and return a single value. For example, 

def sums(x,y):
       return x+y
b = reduce(sums,a)            # b = ((1+2)+3)+4)= 10

The filter(func, s) function filters the elements of s using a filter function, func(), that returns true or false. A new sequence is returned consisting of all elements, x of s, for which func(x) is True. For example:

c= filter(lambda x : x<4, a)            # c = [1, 2, 3]

if func is set to None, the identify function is assumed and filter() returns all elements of s that evaluate to true.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error