itertools module — Python (Part 1)

KodinGyan by Akshima Sharma
5 min readNov 28, 2020

--

In this Part — 1 blog, will share my learning about itertools module infinite and combinatoric iterator.

The Python itertools module is a collection of tools for handling iterators. We must import the itertools module before we can use it.
This module is fast and efficient. Some functions are inspired by functional programming languages like APL, HASKELL, CLOJURE and SML.

Infinite iterators:

Combinatoric iterators :

Terminating Iterator : Covered in next blog link.

Programs

  1. Python Program to print all Possible Combinations from the three Digits.
  2. How to get all possible combinations of a list’s elements?.
  3. How to find all permutations of a string in Python.
  4. How to get all unique combinations of two lists in Python.
  5. How to find all subsets with length n of a given set in Python.
  6. Enumerate using count() and zip function.

Infinite iterators:

1. count() — infinite iterator

  >>>count([start=0, step=1])

count() — may take two values- start and step. It then returns a sequence of values from start, with intervals the size of step.

from itertools import count
for i in count(10,2):
print(i)
if i>25: break

infinite loop using itertools : if we don’t provide break statement, it will continue forever.
count function with no arguments, start iterate with 0 and with one argument means start value.

from itertools import count
for i in count():
print(i)
for i in count(2):
print(i)

2. Cycle — infinite iterator

cycle() makes an iterator from elements from an iterable, and save a copy of each. It restarts printing from the beginning again when all elements are printed in a cyclic manner.

Example using List and String :

from itertools import cycle
for i in cycle([‘red’,’green’,’blue’]):
print(i)
### ------------------------------------------------------>>> import itertools
>>> count = 0
>>> for i in itertools.cycle(‘KodingGyan’):
if count > 11:
break
else:
print(i, end = “ “)
count += 1
K o d i n g G y a n K o

next() function — use next function to fetch data from iterator

import itertools
List1 = [‘Koding ‘, ‘Gyan\n’]
iterators = itertools.cycle(List1)
for i in range(12):
print(next(iterators), end = “”)
Output:
Koding Gyan
Koding Gyan
Koding Gyan
Koding Gyan
Koding Gyan
Koding Gyan

3. repeat() function — repeat element elem n-times or endlessly into the iterator.

repeat(object,[times])

Example :

from itertools import repeat
for i in repeat(‘Red’,3):
print(i)

To create list using repeat function:

import itertools 
List1 = list(itertools.repeat(100, 10)) # repeat 100 , 10 times
print(List1)
Output: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

repeat() function commonly use with map() or zip().

import itertools 
L1 = list(map(pow, range(15), itertools.repeat(2)))
print(L1)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196]

Combinatoric iterators —

  1. product(*iterables, repeat=1) — product() returns the cartesian product of the input iterables. This is equivalent to a nested for-loop.
import itertools 
for i in itertools.product([1,2,3],[4,5,6]):
print(i)
Output:
(1, 4)
(1, 5)
(1, 6)
(2, 4)
(2, 5)
(2, 6)
(3, 4)
(3, 5)
(3, 6)
import itertools
List1 = list(itertools.product([1, 2, 3], repeat = 2))
print(List1)
List2 = list(itertools.product(['Koding', 'Gyan'],'#'))
print(List2)
Output:
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
[(‘Koding’, ‘#’), (‘Gyan’, ‘#’)]

2. permutations(iterable,r=None) — permutations() returns r-length permutations of elements in the iterable.

from itertools import permutations
for i in permutations(‘ABCD’):
print(i)
List1 = list(permutations(range(3), 2))
print(List1)
List2 = list(permutations([1, ‘Python’], 2))
print(List2)
Output:
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
[(1, ‘Python’), (‘Python’, 1)]

3. combinations(iterable,r) — This function returns subsequences of length r from the elements of the iterable.

from itertools import combinations
for i in combinations(‘ABCD’,2):
print(i)
Output:
(‘A’, ‘B’)
(‘A’, ‘C’)
(‘A’, ‘D’)
(‘B’, ‘C’)
(‘B’, ‘D’)
(‘C’, ‘D’)
List1 = list(combinations([‘@’, 2], 2))
print(List1)
Output: [(‘@’, 2)]List1 = list(combinations(['@', 2], 1))
print(List1)
Output : [('@',), (2,)]

4. combinations_with_replacement(iterable, r) — This returns r-length subsequences of elements of the iterable, where individual elements may repeat.

from itertools import combinations_with_replacement
for i in combinations_with_replacement (‘ABCD’,2):
print(i)
Output:
(‘A’, ‘A’)
(‘A’, ‘B’)
(‘A’, ‘C’)
(‘A’, ‘D’)
(‘B’, ‘B’)
(‘B’, ‘C’)
(‘B’, ‘D’)
(‘C’, ‘C’)
(‘C’, ‘D’)
(‘D’, ‘D’)

Programs :

Examples :

1. Python Program to print all Possible Combinations from the three Digits

from itertools import permutationsc1 = permutations([1, 2, 3], 3)
for i in c1:
print(i)
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
# --------------------------------------------------- #from itertools import combinations_with_replacement
c1 = combinations_with_replacement([1, 2, 3], 2)
for i in c1:
print(i)
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 2)
(1, 2, 3)
(1, 3, 3)
(2, 2, 2)
(2, 2, 3)
(2, 3, 3)
(3, 3, 3)

2. How to get all possible combinations of a list’s elements?

 import itertools
L1 = [1,2,3]
for L in range(0, len(L1)+1):
for i in itertools.combinations(L1,L):
print(i)
Output: ()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)

3. How to find all permutations of a string in Python

import itertoolsL1 = []ch = itertools.permutations(“abc”)for i in ch:string = “”.join(i)L1.append(string)print(L1)[‘abc’, ‘acb’, ‘bac’, ‘bca’, ‘cab’, ‘cba’]

4. How to get all unique combinations of two lists in Python

import itertoolslist1 = [“a”, “b”, “c”]list2 = [1, 2]list3 = []list1_a = itertools.permutations(list1, len(list2))for i in list1_a :temp = zip(i, list2)list3.append(list(temp))print(list3)Output: 
[[(‘a’, 1), (‘b’, 2)], [(‘a’, 1), (‘c’, 2)], [(‘b’, 1), (‘a’, 2)], [(‘b’, 1), (‘c’, 2)], [(‘c’, 1), (‘a’, 2)], [(‘c’, 1), (‘b’, 2)]]

5. How to find all subsets with length n of a given set in Python

import itertools
L1 = {“a”, “b”, 1, 2}
data = itertools.combinations(L1, 2)
L1_subset = set(data)
print(L1_subset)
{(1, 2), (‘a’, ‘b’), (2, ‘b’), (1, ‘b’), (‘a’, 2), (‘a’, 1)}

6. Enumerate using count() and zip function

import itertoolsmy_list =[“Koding”, “Gyan”]
for i in zip(itertools.count(start = 1, step = 1), my_list):
print(i)
Output:
(1, 'Koding')
(2, 'Gyan')

Hope you like it. Please check python Iterator Part — II.

Happy Learning .

--

--

KodinGyan by Akshima Sharma
0 Followers

I am Akshima Sharma, having more than 12+ years of experience in Teaching, development, Testing and Quality.