Python map is very useful built-in python function to achieve complex stuff over a list in very short and elegant way. Note that map applies to any iterable (e.g. list). We’ll use list for the purpose of this tutorial.
map(function, iterable, ...)
The function should take one or more arguments (depending upon how many iterables are passed) and should return new value.
Here are some examples.
map example with one list using function
Given a list of numbers get a new list with items squared using function.
def square(x): return x*x a = [1,2,4,10] b = map(square, a) print b
map example with one list using lambda
Given a list of numbers get a new list with items squared using lambda.
a = [1,2,4,10] b = map(lambda x: x*x, a) print b
map example with two lists
Given two lists of numbers get a new list where items are sum of items from these two lists.
a = [1,2,4,10] b = [2,2,3,3] new = map(lambda x, y: x+y, a, b) print new
Note that if you are working on large data then it would be more memory efficient to use itertools imap which calls map function lazily.