Oct-20-2024, 09:04 PM
An infinite iterator is any iterator that can go on yielding values indefinitely. This means that the iterator will never raise the StopIteration exception because there will always be a value to be yielded.
The itertools module provides three functions to create infinity iterators:
The cycle() function creates an iterator that yields the elements of the target iterable in a cyclic manner. When the end is reached, the iteration moves back to the start of iterable.
The itertools module provides three functions to create infinity iterators:
- cycle
- count
- repeat
The cycle() function creates an iterator that yields the elements of the target iterable in a cyclic manner. When the end is reached, the iteration moves back to the start of iterable.
import itertools data = ['Python', 'Java', 'Kotlin'] obj = itertools.cycle(data) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj))
Output:Python
Java
Kotlin
Python
Java
Kotlin
Python
The itertools.count() generates infinite numbers given a starting point and the skip/step value.import itertools nums = itertools.count(0, 20) print(next(nums)) print(next(nums)) print(next(nums)) print(next(nums)) print(next(nums)) print(next(nums)) #this can go on indefinitely
Output:0
20
40
60
80
100
Finally, the itertools.repeat() function repeats a value for a given number of times or indefinitely if the number of times is not given.import itertools obj = itertools.repeat('Python') print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) #this can go on indefinitely
Output:Python
Python
Python
Python
Python
Python