Itertools is a module in python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables.
This module incorporates functions that utilize computational resources efficiently. Using this module also tends to enhance the readability and maintainability of the code.
The itertools module needs to be imported prior to using it in the code.
Count: This function takes two optional arguments and returns an iterator.
If the arguments are not provided then (by default)
start will be set to 0 and
step will be set to 1.
#print the first four even numbers import itertools result = itertools.count(start = 0, step = 2) for number in result: # termination condition if number < 8: print (number) else: break
Cycle: This function takes in an iterable and goes over it indefinitely.
# print 2 three times import itertools result = itertools.cycle('12345') counter = 0 for number in result: # termination condition if counter < 10 : print (number) counter = counter + 1 else: break
Repeat: This function takes an iterable and iterates over it indefinitely. There are two main differences between cycle and repeat:
timesparameter that can be used as a termination condition.
# print hello two times import itertools result = itertools.repeat('hello', times = 2) for word in result: print (word)
These include but are not limited to
Chain: This function accepts a variable number of iterables and loops through all of them, one by one.
# iterate over three lists import itertools list_one = ['a', 'b', 'c'] list_two =['d', 'e', 'f'] list_three = ['1', '2', '3'] result = itertools.chain(list_one, list_two, list_three) for element in result: print (element)
Compress: This function takes in an iterable and a selector, and returns an iterable with only those items for which the corresponding selector value is true.
#find the names of people who have the flu import itertools names = ['Alice', 'James', 'Matt'] have_flu = [True, True, False] result = itertools.compress(names, have_flu) for element in result: print (element)
DropWhile: An iterable and a function (predefined or lambda) is passed to it. Based on the condition inside the function,
dropwhile keeps on dropping values from the iterable until it encounters the first element that evaluates to false.
import itertools my_list = [0, 0, 1, 2, 0] result = itertools.dropwhile(lambda x: x == 0, my_list) for elements in result: print (elements)
View all Courses