Python Forum
Infinity iterators with itertools module
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Infinity iterators with itertools module
#1
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:
  • 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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020