Use of Python's map(),zip(), lambda() and filter()

When I started to use python, there are always zip, map, lambda when I looked the web for a solution. Working of these functions are always magic for me. In this post, we are going to talk about some of important but not well known. These functions can be very helpful in tedious situation. This would be helpful for beginner programmer. Let's get them one by one.


The simplest explanation of zip() is that, it takes some iterables and return a list containing the combined value from iterables. An iterable may be either a sequence, a container which supports iteration, or an iterator. Python Docs for zip()

Let's check an example:

print zip(x,y)


[(1, 21), (2, 12), (3, 33), (19, 4), (0, 5), (6, 46), (7, 22), (8, 18)]

It will return a list of tuples where element of each tuple belong to given inputs(here iterables x and y).


lambda is just a shorten way to create an anonymous function(i.e. functions that are not bound to a name).
Basic syntax :lambda (input) : (expression)
so if you like to add things then the above expression become lambda a,b,c: a+b+c . Let's Do an example

fun1= lambda a,b,c: a+b+c
print fun1(2,4,5)



Isn't it the simplest way to create a small function. Python Docs for lambda()


Basic syntax: map(function, iterable...).It apply(map) the given function to every iterable and return the result as a list. Python Docs for map()

Let's Check this with an example. first define a function

def squre(x):
    return x*x

Now Call the map

z= map(squre, y)
print z


[441, 144, 1089, 16, 25, 2116, 484, 324]

Simple isn't, it. Now let's do this in more convenient way.

p= map(lambda x: x*x, y)
print p


[441, 144, 1089, 16, 25, 2116, 484, 324]


Basic syntax: filter(function, iterable...)

It construct a list from those elements of iterable for which function returns true. It apply the given function to every iterable and for the given value in iterable if the function return True, then it will form a list of the output and return that result. Python Docs for filter()

Let's Make it clear with an example. first define our test function

def check_greater(x):
    if x > 15:
        return True

Now Call the filter() with appropriate iterable. Now the output of the filter should be a list in which all elements are greater then 15. Let's Check



(21, 33, 46, 22, 18)

Final Note:

Above function can be very helpful. This post aim to give you an insight about these functions. However practice makes you perfect.Corrections and suggestions are welcome in the comments.