Python Itertools

Tutorial Playlist

In this blog, we will learn we will learn Python itertools in detail.  Python Itertools is used to play with iterators. It is used in Python programs as it is easy to write, fast, and memory efficient.

What are Python itertools?

Python itertools is a module in Python’s standard library that gives us a lot of functions to play with iterators. It helps us to manipulate the iterators according to the project requirements. We can create custom iterators to do some specific tasks.

Let’s learn this concept in detail with an example:

Example: if we have to perform the cartesian product of the two lists, first let us do this by using the normal function

Code:

Python

Output:

Cartesian product : [(1, ‘a’), (1, ‘b’), (1, ‘c’), (2, ‘a’), (2, ‘b’), (2, ‘c’), (3, ‘a’), (3, ‘b’), (3, ‘c’)]

Now let’s do this using iterators:

Python

Output:

Cartesian product using itertools: [(1, ‘a’), (1, ‘b’), (1, ‘c’), (2, ‘a’), (2, ‘b’), (2, ‘c’), (3, ‘a’), (3, ‘b’), (3, ‘c’)]

Now, we can see this with the help of iterools, the code becomes too easy to write and understand. Also for complex calculations, itertools help us to do the calculations faster than normal functions or iterators.

Data Science with Python: Unlock the Power of Data!
Master Python, Analyze Data, and Build Predictive Models for Real-World Success!
quiz-icon

Types of Iterators in Python

Here are the following three types of Iterators provided by this module in Python:

Infinite Iterators

Iterators in Python are used with for loop to iterate through an array, list, tuple, dictionary, etc. Sometimes loops can also run infinitely, then it is called infinite iterators. Python provides 3 types of infinite iterators:

Method Description Output
count(start, step) It begins with the start value and goes with start+step values Eg: count(5,3)
Output: 5,8,11
cycle(iterable) It iterates the value in the form of cycle Eg: cycle(‘ABC’)
Output: A B C A B C A B C….
repeat(val, n) It repeats the value n number of times Eg: repeat(2,4)

Output: 2 2 2 2.

Let’s learn all of these functions with the help of codes:

  1. Count(start, step): this function helps us to print values in the form of an arithmetic progression. Like we are adding a number continuously. This function will run the loop infinitely, if the step is not given, it will take 1 by default.

Code:

Python

Output:

2 7 12 17 22 27 32 37

Explanation: the above code will start printing the value from 2 and go on printing the next fifth element, whenever the loop reaches to 42 it will stop printing.

  1. cycle(iterable): this iterator helps us to print the values in the form of a cycle. Once it goes to the complete its cycle, starts again.

Example:

Python

Output:

A B C A B C A B C A

  1. repeat(val, n): this function prints the val infinitely. And if the value of n is given then prints n number of times only.

Code:

Python

Output:

[‘Intellipaat’, ‘Intellipaat’, ‘Intellipaat’, ‘Intellipaat’]

Combinatoric iterators

There are four combinatoric iterators in Python:

Methods Description Example
product() This function helps us to find the cartesian product of the list product(list1, list2)
permutations() It is used to find the permutation of the list permutation(list1)
combinations() It helps us to print all the possible combinations (without replacement). combinations(‘ABC’, 2)
combinations_with_replacement() It helps us to print the combinations with replacement combinations_with_replacement(“AB”, 2)

Python-Powered Data Science!
Learn Python and Industry-Ready Data Science Techniques to Supercharge Your Career!
quiz-icon

Let’s learn all of these methods with the help of code:

  1. product(): this function is used to find the cartesian product of two lists or arrays.

Code:

Python

Output:

[(‘A’, 2), (‘A’, 5), (‘B’, 2), (‘B’, 5), (‘C’, 2), (‘C’, 5)]

  1. permutations(): this function is used to find the permutations of the list or array.

Code:

Python

Output:

[(‘X’, ‘Y’, ‘Z’), (‘X’, ‘Z’, ‘Y’), (‘Y’, ‘X’, ‘Z’), (‘Y’, ‘Z’, ‘X’), (‘Z’, ‘X’, ‘Y’), (‘Z’, ‘Y’, ‘X’)]

[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]

  1. combinations(): this function is used to find all the possible combinations of the list or array without replacement in sorted order.

Code:

Python

Output:

Pairwise combinations: [(‘A’, 2), (‘A’, ‘B’), (‘A’, 3), (2, ‘B’), (2, 3), (‘B’, 3)]

  1. combinations_with_replacement(): this function includes the replacement of the elements, and then finds the possible combinations of the elements.

Code:

Python

Output:

Pairwise combinations: [(‘A’, ‘A’), (‘A’, 2), (‘A’, ‘B’), (‘A’, 3), (2, 2), (2, ‘B’), (2, 3), (‘B’, ‘B’), (‘B’, 3), (3, 3)]

Terminating Iterator

Here are the following types of terminating iterators in this module.

  1. accumulate(iter, func): this function is used to add the numbers one by one., also we can perform multiplication, subtraction, etc. by default it performs summation of the elements.

Code:

Python

Output:

[1, 3, 6, 10]

[1, 2, 6, 24]

  1. chain(iter): this function helps us to concatenate multiple lists into one list.

Code:

Python

Output:

[1, 2, ‘A’, ‘B’, 3, 4]

  1. chain.from_iterable(iter): this function helps us to iterate on a single list, it would be a list of lists or any other iterable list

Code:

Python

Output:

[1, 2, 3, 4, 5, 6]

  1. compress(data, selectors): it helps us to filter the data based on some given selectors, the selector is a list of boolean values.

Code:

Python

Output:

[‘A’, ‘C’, ‘E’]

  1. zip_longest(*iterables, fillvalue=None): this function helps us to print the list alternatively, and if one list is completed, it will take values from fill value.

Code:

Python

Output:
[(‘A’, ‘1’), (‘B’, ‘2’), (‘X’, ‘3’), (‘X’, ‘4’)]

  1. dropwhile(func, iterable): this function starts printing the value when the function gives us false as the returned value.

Code:

Python

Output:

[3, 4, 5]

  1. tee(iterable, n): this function splits the list into n number of times iterators.

Code:

Python

Output:
[1, 2, 3]

[1, 2, 3]

  1. takewhile(function, iterable): this function is the opposite of dropwhile function, and it starts printing the value whenever the function returns true, it stops printing the value when it returns false value.

Code:

Python

Output:
[1, 2]

  1. starmap(function, tuple list): this function performs some action based on the function given in the arguments on tuples.

Code:

Python

Output:
[8, 9]

  1. pairwise(iterable): this function converts the given input in the form of pairs.

Code:

Python

Output:
[(‘A’, ‘B’), (‘B’, ‘C’), (‘C’, ‘D’), (‘D’, ‘E’)]

  1. islice(iterable, start, stop[, step]): this iterator starts iterating the loop in a specified range that is mentioned in the arguments.

Code:

Python

Output:
[20, 30, 40]

  1. groupby(iterable, key=None): this function helps us to group similar elements together

Code:

Python

Output:

[(‘a’, [‘a’, ‘a’, ‘a’]), (‘b’, [‘b’, ‘b’]), (‘c’, [‘c’, ‘c’])]

  1. filterfalse(function, iterable): it filters the elements from a tuple or list based on some condition, if the condition is false, it takes the element otherwise not.

Code:

Python

Output:
[1, 3, 5]

  1. batched(iterable, n): this function helps us to split the elements into batches of size n, where each batch is returned as a tuple.

Code:

Python

Output:

[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)]

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

So far in this article, we have learned Python itertools and their methods in detail. We have also learned the different types of Python itertools: Infinite, combinators, and Iterators terminating. We have covered all the methods of these iterators in detail. If you want to learn more about Python, you may refer to our Python Course.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.