map function is very useful in Python where we want to perform operations on a list of data items and store the procesed result in another list.
"""
created_at : 16 Feb 2017.
updated_at : 16 Feb 2017.
aim of script : To understand the concept of maps in Python.
coded by : Rishikesh Agrawani.
Python version : 2.7.12
"""
#Interactive mode programming - #1
>>> def square(n):
... return n**2
...
>>> l = [1, 2, 3, 4, 5, 6]
>>> print map(square,l)
[1, 4, 9, 16, 25, 36]
>>>
>>> def cube(n):
... return n**3
...
>>> t = 1,2,3,4,5,
>>> t
(1, 2, 3, 4, 5)
>>>
>>> t = 1,2,3,4,5
>>> t
(1, 2, 3, 4, 5)
>>>
>>> print map(cube,t)
[1, 8, 27, 64, 125, 216]
>>>
>>> def add_elems_of_two_sequences(a,b):
... return a+b
...
>>> print map(add_elems_of_two_sequences,l,t)
[2, 4, 6, 8, 10, 12]
>>>
>>> l2 = [3,6,9,12,15,18]
>>> print map(add_elems_of_two_sequences,l2,t)
[4, 8, 12, 16, 20, 24]
>>>
#Interactive mode programming - #2 (using lambda expression)
>>> sum = lambda a,b:a+b
>>> l = [5,4,3,2,1]
>>> t = 6,7,8,9,10
>>>
>>> print l
[5, 4, 3, 2, 1]
>>>
>>> print t
(6, 7, 8, 9, 10)
>>>
>>> map(sum,l,t)
[11, 11, 11, 11, 11]
>>>
>>> t2 = 3,4,5,6,7
>>> map(lambda a,b:a+b, t,t2)
[9, 11, 13, 15, 17]
>>>
#Interactive mode programming - #3
>>> def table(n):
... return [i*n for i in xrange(1,11)]
...
>>> for l in map(table, [5,10,15,20,25,30]):
... print l
...
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[15, 30, 45, 60, 75, 90, 105, 120, 135, 150]
[20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
[25, 50, 75, 100, 125, 150, 175, 200, 225, 250]
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]
>>>
Let's look at some other examples.The following pyscripts show the basic usgae of lambda expressions and map function.
Define a function that will take 1 number and returns its table. Call map function with function name as 1st argument and a list of numbers from 1 to 10 as 2nd argument.
#Example - 1
def get_table(n): return [n*i for i in range(1,11)] result = map(get_table, [1,2,3,4,5,6,7,8,9,10]) print result print "\n" for l in result: for item in l: print item,"\t", print "\n" """ [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], [3, 6, 9, 12, 15, 18, 21, 24, 27, 30], [4, 8, 12, 16, 20, 24, 28, 32, 36, 40], [5, 10, 15, 20, 25, 30, 35, 40, 45, 50], [6, 12, 18, 24, 30, 36, 42, 48, 54, 60], [7, 14, 21, 28, 35, 42, 49, 56, 63, 70], [8, 16, 24, 32, 40, 48, 56, 64, 72, 80], [9, 18, 27, 36, 45, 54, 63, 72, 81, 90], [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]] 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 """