Types of Itertools
- Infinite iterators
- Finite iterators
- Combinatoric iterators
- Terminating iterators
Now let's look into types of Itertools
Infinite Iterators
This includes
1. Count ([start=0, step=1])
In this, the argument used to give the following result
start, start+step, start+2*step, …
It uses the above equation to give the result, the code for this is given below, and the output shows the result of the code in the same given manner as the equation express
10,12,14,16…
Code:
>>> from itertools import count
>>> for i in count(12,2):
print(i)
if i>20: break

You can also try this code with Online Python Compiler
Run CodeOutput:
12
14
16
18
20
2. Cycle (iterable)
The given Itertools are expressed in the given manner.
p0, p1, … plast, p0, p1, …
It basically prints the string in the following manner:
cycle('ABCD') --> A B C D A B C D ...
Code:
>>> from itertools import cycle
>>> for i in cycle(['rose','garden','beach']):
print(i)

You can also try this code with Online Python Compiler
Run CodeOutput:
rose
garden
beach
rose
garden
beach
rose
garden
beach
3. Repeat (elem [,n])
It basically uses the algorithm as follows
elem, elem, elem, … endlessly or up to n times
It prints the elements repeatedly up to the given parameter specified
Code:
>>> from itertools import repeat
>>> for i in repeat(‘CodingNinjas’,3):
print(i)

You can also try this code with Online Python Compiler
Run CodeOutput:
CodingNinjas
CodingNinjas
CodingNinjas
Finite Itertools
1. Chain(*iterables)
The given Itertools is expressed in the given manner
p0, p1, … plast, q0, q1, …
The argument given will be printed in the following manner
chain('ABC', 'DEF') --> A B C D E F
Code:
>>> from itertools import chain
>>> for i in chain('Hello','Ninjas'):
print(i)

You can also try this code with Online Python Compiler
Run CodeOutput:
H
e
l
l
o
N
i
n
j
a
s
2. Compress(data, selectors)
It creates a data filtering iterator that only returns elements from the data corresponding to elements in selectors that evaluate True.
compress('ABCDEF',[1,0,1,True,0,' '])-->A C D F
Code:
>>> from itertools import compress
>>> for i in compress('CODING',[1,0,1,True,0,' ']):
print(i)

You can also try this code with Online Python Compiler
Run CodeOutput:
C
D
I
G
3. Dropwhile(predicate,iterable)
It creates an iterator that returns each element after dropping elements from the iterable while the predicate is true.
dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
Code:
>>> from itertools import dropwhile
>>> for i in dropwhile(lambda x:x<7,[1,2,7,9,5,3,2,9]):
print(i)

You can also try this code with Online Python Compiler
Run CodeOutput:
7
9
5
3
2
9
Combinatoric Iterators
Combinatoric iterators are used to create combinations and permutations of data. The most commonly used functions are product, permutations, combinations, and combinations_with_replacement.
- product(*iterables, repeat=1)
It creates a Cartesian product of the provided iterables.
Code:
from itertools import product
for p in product('AB', repeat=2):
print(p)

You can also try this code with Online Python Compiler
Run Code Output:
('A', 'A')
('A', 'B')
('B', 'A')
('B', 'B')
2. permutations(iterable, r=None)
Returns successive r-length permutations of elements in the iterable.
Code:
from itertools import permutations
for p in permutations('ABC', 2):
print(p)

You can also try this code with Online Python Compiler
Run CodeOutput:
('A', 'B')
('A', 'C')
('B', 'A')
('B', 'C')
('C', 'A')
('C', 'B')

You can also try this code with Online Python Compiler
Run Code
3. combinations(iterable, r)
Generates r-length combinations of elements in the iterable.
Code:
from itertools import combinations
for c in combinations('ABC', 2):
print(c)

You can also try this code with Online Python Compiler
Run CodeOutput:
('A', 'B')
('A', 'C')
('B', 'C')
4. combinations_with_replacement(iterable, r)
Generates r-length combinations of elements in the iterable allowing individual elements to be repeated more than once.
Code:
from itertools import combinations_with_replacement
for c in combinations_with_replacement('AB', 2):
print(c)

You can also try this code with Online Python Compiler
Run CodeOutput:
('A', 'A')
('A', 'B')
('B', 'B')
Terminating Iterators
Terminating iterators are used to process elements of an iterator until a condition is met. They include functions like accumulate, chain, slice, and take a while.
- accumulate(iterable[, func])
Makes an iterator that returns accumulated sums, or accumulated results of other binary functions.
Code:
from itertools import accumulate
import operator
for i in accumulate([1,2,3,4,5], operator.mul):
print(i)

You can also try this code with Online Python Compiler
Run CodeOutput:
1
2
6
24
120
2. chain(*iterables)
It combines several iterables into a long sequence.
Code:
from itertools import chain
for i in chain('Hello', 'World'):
print(i)

You can also try this code with Online Python Compiler
Run CodeOutput:
H
e
l
l
o
W
o
r
l
d
3. islice(iterable, start, stop[, step])
Make an iterator that returns selected elements from the iterable.
Code:
from itertools import islice
for i in islice('ABCDEFG', 2, None):
print(i)

You can also try this code with Online Python Compiler
Run CodeOutput:
C
D
E
F
G
4. takewhile(predicate, iterable)
Makes an iterator and returns elements from the iterable only as long as the predicate is true.
Code:
from itertools import takewhile
for i in takewhile(lambda x: x < 5, [1, 4, 6, 4, 1]):
print(i)

You can also try this code with Online Python Compiler
Run Code Output:
1
4
Each of these iterators from the itertools module is highly useful for specific tasks in data processing, particularly when dealing with large datasets or complex logic.
You can also read about the Multilevel Inheritance in Python, Swapcase in Python
Frequently Asked Questions
What are the itertools in Python?
itertools in Python is a module that provides efficient looping constructs for creating and using iterators in data processing tasks.
What is the use of Itertools.cycle in Python?
Itertools.cycle repeatedly cycles through an iterable indefinitely, returning each element in sequence without stopping.
What is an iterator in Python?
An iterator in Python is an object that enables traversal over the elements of a container, typically using a loop, one at a time.
Conclusion
In this article, we talked about the itertools module in Python. It's a library that has a bunch of helpful functions for working with iterators. These functions let you create, filter, and manipulate sequences of elements in a way that's both easy to read and efficient.
Recommended Readings: