Python map examples

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.

Usage: 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
[1, 4, 16, 100]
Env: Python 2.7.6

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
[1, 4, 16, 100]
Env: Python 2.7.6

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
[3, 4, 7, 13]
Env: Python 2.7.6

Additional notes

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.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments