Some useful itertools functions in python

One of my favorite module in python is itertools as it has plenty of useful function to use.

I am highlighting some of the  function which I used often. itertools mostly used when you want to iterate over some sort of data. There are lot of function which been implemented in itertools, however there are some which are really useful. Here are the list of some useful function:


Computes the cartesian product of input iterables. It’s equivalent to nested for loop.

Let’e write some code:

from itertools import product
for item in product('abc', 'def'):
    print item
output >>>
('a', 'd') ('a', 'e') ('a', 'f') ('b', 'd') ('b', 'e') ('b', 'f') 
('c', 'd') ('c', 'e') ('c', 'f')
Explanation: product basically create the combination of each char
              from 'abc' with each char of 'def'

You can write above code as this way in python:

for first_str in 'abc':
   for second_str in 'def':
        print (first_str, second_str)

Using product make it more pythonic.

itertools.permutations(iterable[, r])

In simple term, it basically find all the permutation of any given word. Permutations are printed in a lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be produced in a sorted order.

Let’e look out the example:

Let’s say you need to find all the permutation of any string called: ‘abc’ or list as [‘a’, ‘b’, ‘c’]:

from itertools import permutations
print [word for word in permutations('abc')] // or ['a', 'b', 'c']
('a', 'b', 'c') ('a', 'c', 'b') ('b', 'a', 'c') ('b', 'c', 'a') 
('c', 'a', 'b') ('c', 'b', 'a')
If I need to find permutation of any list or string, I most of the time
use permutations instead of writing my own code.

If you want to find the permutation of any string, you would write same in python as this, which is long code to write:

def get_permutation(head, tail=''):     
     if len(head) == 0: 
          print tail     
         for item in xrange(len(head)):             
              get_permutation(head[0:item] + head[item+1:], tail + 

itertools.combinations(iterable, r)

as name suggest, it basically give all combination of strings or lists.Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Let’s say one of the example to use it:

from itertools import combinations
print [(key, item) for key, item in combinations('abc', 2)]
[('a', 'b'), ('a', 'c'), ('b', 'c')]
It basically create all the combination of specific string or list wihtout

itertools.groupby(iterable[, r])

This is what python docs says, which gives good information:

The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.

let’s go through the example:

from itertools import groupby
print [print (item, len(list(freq))) for item, freq in groupby('aabccc')]
Output >>>
[('a', 2), ('b', 1), ('c', 3)]
groupby basically group the common words and find the frequency of the 
each word.

You can check other function of itertools in python doc here:



2 thoughts on “Some useful itertools functions in python

  1. Good going Sunil, I am reading your posts and they are kinda helpful to me to understand the things in Python. Keep going.


Leave a Reply to Raja Vairaashtak Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s