Python itertools imap examples

Python itertools imap is efficient way of mapping and looping over a large iterable. Here is the usage for imap:

itertools.imap(function, *iterables)

The function should take one or more arguments (depending upon how many iterables are passed) and should return new value.

Here are some examples.

itertools imap with function on one list

Given a list of numbers get a new list with items squared using function.

import itertools
def square(x):
  return x*x
a = [1,2,4,10]
b = itertools.imap(square, a)
print b
for i in b:
  print i
Env: Python 2.7.6

itertools imap with lambda one one list

Given a list of numbers get a new list with items squared using lambda.

import itertools
a = [1,2,4,10]
b = itertools.imap(lambda  x: x*x, a)
print b
for i in b:
  print i
<itertools.imap object at 0x7fac22c78a50>
1
4
16
100
Env: Python 2.7.6

itertools imap on two lists

Given two lists of numbers get a new list where items are sum of items from these two lists.

import itertools
a = [1,2,4,10]
b = [2,2,3,3]
new = itertools.imap(lambda  x, y: x+y, a, b)
print new
for i in new:
  print i
Env: Python 2.7.6

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

Comments

Click here to write/view comments