Python

Python Itertools

The iterator-based code is more efficient than the general code because it increases the performance of the program by reducing the use of memory. The itertools is a very useful module of Python that is used to generate different types of iterator. The functions of this module are used on the iterator to generate a more complex iterator. Some useful functions of the Itertools module have shown in this tutorial by using multiple python scripts.

Types of Iterator:

Different types of iterators in the itertools module have given below:

  1. Infinite iterators
  2. Combinatoric iterators
  3. Terminating iterators

Infinite Iterators:

The iterator objects are traversed by using the ‘for’ loop. List, dictionary, tuple are examples of the iterator object. The infinite iterators are called the infinite iterator. Some infinite iterator functions are mentioned below.

repeat (value [, num])

The first argument of this function is mandatory, and the second argument is optional. It is used to repeat the values of the iterator object infinite times.

cycle ()

It is used to print the values of the iterator object in cyclic order.

count (start [, step])

The first argument of this function is mandatory, and the second argument is optional. It is used to print the values of the iterator object from the start value to infinite times. If the second argument step is given, then the values will be printed by skipping that number of steps.

Example-1: Use of infinite iterators

Create a python file with the following script to know the ways of using repeat() and the cycle() function. Here, the repeat() function will print the character ‘*’ 10 times, and the cycle() function will circularly print the list values.

# Include itertools module
import itertools

print("Print a character for multiple times using repeat():")
# Using repeat() function
print(list(itertools.repeat('*', 10)))

# Define a list of numbers
listData = [1, 2, 3, 4, 5]
# Define a iterator to read the list in circular way
iterator = itertools.cycle(listData)
# Print the list data based on the range value
print("\nPrint the list values in circular way:")
for iin range(12):
# Print the values using next() method and iterator object
print(next(iterator), end="\t")

Output:

The following output will appear after executing the above script. In the first output, The character ‘*’ value has been repeated 10 times by using the repeat() function. In the second output, the list values are printed in circular order in 12 iterations of the ‘for’ loop.

Combinatoric iterators:

The recursive generator is used to simplify the complex combinatorial constructs. The following are examples of combinatoric iterators.

  1. Cartesian products
  2. Permutations
  3. combinations

product():

It is used to calculate the Cartesian product of input iterable objects. The optional repeat keyword argument is used to repeat the values of all possible combinations. It returns output in the form of tuples.

permutations():

It is used to print all possible permutations of an iterable object.

combinations():

It is used to print all the possible combinations without replacing the iterable object.

Example-2: Use of product() to calculate the Cartesian product

Create a python file with the following script to check the uses of the product() function to calculate the Cartesian product of the iterable object. The first product() function will calculate the Cartesian product of a list and a character. The second product() function will calculate the Cartesian product of a list with the repeat keyword. The third product() function will calculate the Cartesian product of a string of two characters and a list.

# Import product from itertools
from itertoolsimport product

# Print the cartesian product of a container and character
print("Calculate the cartesian product of a container and character:")
print(list(product([1, 2, 3], 'A')))

# Print the cartesian product of a container using repeat keyword
print("\nCalculate the cartesian product using repeat Keyword:")
print(list(product(['Python', 'LinuxHint'], repeat=2)))

# Print the cartesian product of a character and container
print("\nCalculate the cartesian product of a character and container:")
print(list(product('AB', [1, 2, 3])))

Output:

The following output will appear after executing the above script. In the first output, three tuples were generated using three items of the list and the character, ‘A’ because 31 is 3. In the second output, four tuples were generated by using two list items with the repeat value, 2 because 22 is 4. In the third output, six tuples were generated using the string, ‘AB’, and the list of three items because 32 is 6.

Terminating iterators:

It is used to work with the small input sequence, and the output is generated based on the function used by the iterator. The chain() function is one of the functions used for the terminating iterator.

chain(iter1, iter2):

It is used to print all the values of the iterable object in the form of a chain.

Example-3: Use of chain() function to combine two list values

Create a python file with the following script to merge the values of the two lists by using the chain() function. Two lists contain the name of the students. The values of the second list will be added at the end of the first list before printing the output.

# Import product from itertools
import itertools

# Declare the first student list
std_list1 = ['Mehrab Hossain', 'Riya Chakroborty', 'MinhazKazi']

# Declare the second student list
std_list2 = ['Zinia Rahman', 'Sadia Akter']

print("The values of the merged list: ")
# Merge the two list using chain() function
print(list(itertools.chain(std_list1, std_list2)))

Output:

The following output will appear after executing the above script. The merged values of the list have been printed in the output.

Conclusion:

The purposes of the itertools module and the uses of some itertools functions have been shown in this tutorial by using multiple examples to help the python users to know the use of this module.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.