Exploring Infinite Iterators in Python's itertools - KDnuggets

Exploring Infinite Iterators in Python’s itertools – KDnuggets

Source Node: 2319057

Exploring Infinite Iterators in Python's itertools
Image by Author

Infinite iterators, as the name suggests, are special types of iterators that can continue generating values indefinitely. Unlike the in-built iterators like lists, tuples, and dictionaries that eventually reach an end, infinite iterators can produce an unending stream of values. Such iterators are also sometimes referred to as infinite generators or sequences. They find use in various scenarios for solving problems involving simulation, generating sequences, processing real-time data, and more.

The Itertools library in Python provides three in-built infinite iterators.

  • Count
  • Cycle
  • Repeat

The count() function generates infinite numbers starting from the specified value and step size. The syntax for the count iterator is as follows:

itertools.count(start=0, step=1)

 

It has two optional parameters: “start” and “stop,” with default values of 0 and 1, respectively. “Start” refers to the initial value of your counting, while “step” represents the increment used to advance the count.

Let us analyze the function with the help of an example. If you need to generate a sequence of numbers with a step size of 3 just like the table of 3, you can use this code:  

from itertools import count counter = count(3,3) print("The table of 3 is:")
for i in range(10): print(f"3 x {i+1} = {next(counter)}")

Output

The table of 3 is: 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15 3 x 6 = 18 3 x 7 = 21 3 x 8 = 24 3 x 9 = 27 3 x 10 = 30

The cycle() function creates an iterator and repeats all the items of the passed container indefinitely. Here is the syntax for the cycle iterator:

itertools.cycle(iterable)

 

The “iterable” parameter here can be any iterable data structure in Python, such as lists, tuples, sets, and more. Consider an example of a traffic light controller system that continuously cycles through different lights. No different actions are performed while cycling through the different colored lights. We will use a wait time of 5 seconds to display our results.

from itertools import cycle
import time lights = ["red", "green", "yellow"]
cycle_iterator = cycle(lights) while True: print(f"Current light is: {next(cycle_iterator)}") time.sleep(5)

Output

Current light is: red Current light is: green Current light is: yellow Current light is: red Current light is: green Current light is: yellow

 

You will see this output after approximately 25 seconds.

The repeat() function generates a sequence of the specified number infinitely. It is useful when you need to generate a single value indefinitely. The syntax for the repeat iterator is as follows:

itertools.repeat(value, times=inf)

 

We have two parameters here: “value” is for the number you want to generate infinitely, while “times” is an optional parameter for how many times you want to generate that number. The default value for “times” is infinity, indicating that it will print endlessly unless you explicitly specify a finite number. For example, if you need to generate the number “9” three times, then the following code can be used:

from itertools import repeat iterator = repeat(9, 3) for value in iterator: print(value)

Output

These infinite iterators are extremely helpful in scenarios when we need to work with streams of data. The “count”, “cycle” and “repeat” iterators provide us the ability to solve problems more efficiently and elegantly. Although using them requires necessary caution as they can lead to infinite loops, when used thoughtfully they can be a valuable resource for solving programming problems. I hope you enjoyed reading this article and if you have anything to share feel free to drop your suggestions in the comment box below.
 
 
Kanwal Mehreen is an aspiring software developer with a keen interest in data science and applications of AI in medicine. Kanwal was selected as the Google Generation Scholar 2022 for the APAC region. Kanwal loves to share technical knowledge by writing articles on trending topics, and is passionate about improving the representation of women in tech industry.
 

Kanwal Mehreen is an aspiring software developer with a keen interest in data science and applications of AI in medicine. Kanwal was selected as the Google Generation Scholar 2022 for the APAC region. Kanwal loves to share technical knowledge by writing articles on trending topics, and is passionate about improving the representation of women in tech industry.

Time Stamp:

More from KDnuggets