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.
These include count
, cycle
and repeat
.
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 numbersimport itertoolsresult = itertools.count(start = 0, step = 2)for number in result:# termination conditionif number < 8:print (number)else:break
Cycle: This function takes in an iterable and goes over it indefinitely.
# print 2 three timesimport itertoolsresult = itertools.cycle('12345')counter = 0for number in result:# termination conditionif counter < 10 :print (number)counter = counter + 1else:break
Repeat: This function takes an iterable and iterates over it indefinitely. There are two main differences between cycle and repeat:
times
parameter that can be used as a termination condition.# print hello two timesimport itertoolsresult = itertools.repeat('hello', times = 2)for word in result:print (word)
These include but are not limited to chain
, compress
and dropwhile
.
Chain: This function accepts a variable number of iterables and loops through all of them, one by one.
# iterate over three listsimport itertoolslist_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 fluimport itertoolsnames = ['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 itertoolsmy_list = [0, 0, 1, 2, 0]result = itertools.dropwhile(lambda x: x == 0, my_list)for elements in result:print (elements)
Free Resources