Python Tutorial

Wednesday, November 11, 2015

map keyword

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items.


All source code available on github
intArray = [2, 3, 4, 6, 5, 7]
strArray = ['2', '3', '4', '6', '5', '7']

# square all elements of array
print map(lambda x:x**2, intArray)

# convert string array to int array
print map(int, strArray)

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

# sum two array elements  by index
print map(lambda x, y : x+y, a, b)


Output:
[4, 9, 16, 36, 25, 49]
[2, 3, 4, 6, 5, 7]
[5, 7, 9]