It provides a list of iterator
for some common tasks like permutations, combinations, infinite iterators, cycle looping, etc.
import itertools
from datetime import datetime
import time
count(start=0,step=1)
- Keeps on increasing count by step
from start
until loop is stopped by some condition.cycle(iterable)
- keeps on looping through iterable
infinite times. After the last element has used it again starts from the first one like a cycle. repeat(object[,times=None])
- Keeps on repeating object infinite times until stopped by some loop. If times are provided as some integer then it repeats that many times.result = []
for i in itertools.count(5, 5):
if i <= 100:
result.append(i)
else:
break
print(result)
result = []
for i in itertools.cycle(range(1,6)):
if len(result) < 15:
result.append(i)
else:
break
print(result)
result = []
for i in itertools.cycle(['B','O','B']):
if len(result) < 15:
result.append(i)
else:
break
print(result)
print(list(itertools.repeat('A', 5)))
print(list(itertools.repeat([1,2], 5)))
print(list(itertools.repeat({'key':'val'}, 7)))
accumulate(iterable[,func])
- It returns accumulated sum of numbers if func
is not provided else applies binary func
to elements of iterable
.chain(*iterables)
- It loops through all iterables
passed as arguments and returns elements of each one by one in sequence they were given input.compress(data,selectors)
- It loop through data
one by one and returns only that elements for which element with same index in selectors
return True
.print(list(itertools.accumulate(range(5,15))))
print(list(itertools.accumulate(range(5,15), lambda x,y : x*y)))
print(list(itertools.accumulate(range(5,15), lambda x,y : y/x)))
print(list(itertools.accumulate('ABCD')))
print(list(itertools.accumulate('ABCD', lambda x,y : [x,y])))
print(list(itertools.chain(range(1,4),range(4, 1,-1),'ABCDE')))
print(list(itertools.compress(range(5,0,-1),[True,False,True,False,True])))
print(list(itertools.compress(range(5,0,-1),[True,None,None,False,True])))
print(list(itertools.compress(range(5,0,-1),[0,1,1,1,0])))
print(list(itertools.compress(range(5,0,-1),[[],[1,2],[],[1,2,3],[]])))
print(list(itertools.compress(range(5,0,-1),[{},{'key':'val'},{'key':'val'},{},{}])))
dropwhile(predicate,iterable)
- It drops element as long as predicate condition
is True
and then it returns all elements.filterfalse(predicate,iterable)
- It returns only those elements from iterable
for which predicate condition
is False
.print(list(itertools.dropwhile(lambda x: x<2, range(1,6))))
print(list(itertools.dropwhile(lambda x: x == 2, range(1,6)))) ## Make a note here that first condition itself is False hence returns all elements
print(list(itertools.dropwhile(lambda x: (x**2) < 5, range(1,6))))
print(list(itertools.dropwhile(lambda x : x in ['A','E','I','O','U'], 'EABCD')))
print(list(itertools.filterfalse(lambda x: x%2==0, range(1,6))))
print(list(itertools.filterfalse(lambda x: x//2 < 2, range(1,6))))
print(list(itertools.filterfalse(None, range(6))))
print(list(itertools.filterfalse(lambda x : x in ['A','E','I','O','U'], 'ABCDE')))
groupby(iterable,key=None)
- Returns an iterator which consists of key, group
pair from iterable
based on function provided as key
which generates key
in pair. If key
is not provided then it's set to identity function(lambda x: x
). iterable
should be sorted to get proper results/grouping. Elements should be in sorted order to get proper groups.for key,group in itertools.groupby([2,2,2,3,3,4,4]):
print(str(key)+ ' : ' + str(list(group)))
for key,group in itertools.groupby(['Arial','Ariel','Bad','Bed','Cat','Catch'],key=lambda x: x[0]):
print(str(key)+ ' : ' + str(list(group)))
class Employee(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name + ' : , Age : '+str(self.age)
e1 = Employee('Sunny',27)
e2 = Employee('Sumit',27)
e3 = Employee('Anup',35)
e4 = Employee('Ashwin',35)
e5 = Employee('Rohit',38)
e6 = Employee('Irfan',38)
e7 = Employee('Ethesh',22)
e8 = Employee('Kaushal',45)
for key,group in itertools.groupby([e1,e2,e3,e4,e5,e6,e7,e8], key=lambda x: x.age):
group_desc = [str(item) for item in group]
print(str(key)+ ' : ' + str(group_desc))
for key,group in itertools.groupby([e1,e2,e3,e4,e5,e6,e7,e8], key=lambda x: x.name[0]):
group_desc = [str(item) for item in group]
print(str(key)+ ' : ' + str(group_desc))
islice(iterable, stop)
- Loops through iterable
and returns element from begining till stop
index.islice(iterable, start,stop[,step])
- Loops through iterable
from start
index till stop
index using step
for item skippingstarmap(function,iterable)
- executes function
using each argouments of iterable
as argument to function
.takewhile()
- It's reverse of dropwhile()
function. It returns element until condition is True
whereas dropwhile() drops element while condition is True
and then returns elements.print(list(itertools.islice('ABCDE',3)))
print(list(itertools.islice('ABCDE',0,2)))
print(list(itertools.islice('ABCDE',0,None, 3)))
print(list(itertools.starmap(lambda x: x%2, [(2,),(3,),(4,),(5,),(6,),(7,),(8,)])))
print(list(itertools.starmap(lambda x: datetime.fromtimestamp(x), [(6,),(60,),(3600,)])))
print(list(itertools.starmap(lambda x: time.gmtime(x),[(6,),(60,),(3600,)])))
print(list(itertools.takewhile(lambda x: x<2, range(1,6))))
print(list(itertools.takewhile(lambda x: x == 2, range(1,6)))) ## Make a note here that first condition itself is False hence returns no elements
print(list(itertools.takewhile(lambda x: (x**2) < 5, range(1,6))))
print(list(itertools.takewhile(lambda x : x in ['A','E','I','O','U'], 'EABCD')))
tee(iterable,n=2)
- It returns n independent iterables from single iterable
.zip_longest(*iterable, fill_value=None)
- It's same as zip()
function but returns elements same as longest sequence and fills value specified by fill_value
in other small lists.result = itertools.tee([1,2,3,4], 4)
print([list(item) for item in result ])
result = itertools.tee('ABCDE', 3)
print([list(item) for item in result ])
print(list(itertools.zip_longest([1,2,3,4,5,6],[1,2,4],[1,2,3,4,5])))
print(list(itertools.zip_longest([1,2,3,4,5,6],[1,2,4],[1,2,3,4,5],'NONE')))
print(list(itertools.zip_longest([1,2,3,4,5,6],[1,2,4],[1,2,3,4,5],'NA')))
product(*iterables)
- Returns cartesian product of input iterables
. To compute product of iterable
with itself specify repeat
with number of times you want to repeat.permutations(iterable,r=None)
- It returns all possible permutations of lenght r
of iterable
. If r
is not specified then all possible permutation of whole iterable
is returned.combinations(iterable,r)
- Returns all combinations of length r
of iterable
. combinations_with_replacement(iterable,r)
- Returns all combinations of length r
of iterable
with allowing replacement more than once. print(list(itertools.product([1,2,3,4],[4,3,2,1])))
print(list(itertools.product([1,2,3,4],[4,3,2,1],[7,8,9])))
print(list(itertools.product([1,2,3,4],[4,3,])))
print(list(itertools.product([1,2,3,4],[4,3,],repeat=2)))
print(list(itertools.product('CBA','ABC')))
print(list(itertools.product([1,2,3,4],repeat=3)))
print(list(itertools.permutations('ABCDE', r=2))) ## Order of elements does matter in permutations
print(list(itertools.permutations('ABC')))
print(list(itertools.combinations('ABCDE', r=2))) ## Order of elements does not matter in combintations
print(list(itertools.combinations_with_replacement('ABCDE', r=2))) ## Make a note that element was replaced hence there are extra entry of element with itself.
print(list(itertools.combinations('ABC', r=3)))
If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.
When going through coding examples, it's quite common to have doubts and errors.
If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.
You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.
If you want to