In some cases, we need to get an infinite iterable. There are 3 functions that are helpful:
itertools.repeat(): Generate the same item repeatedly
For example, we can get three same “Yang” as follows:
import itertools
print(list(itertools.repeat('Yang', 3)))
# ['Yang', 'Yang', 'Yang']
itertools.cycle(): Get an infinite iterator by cycling
The itertools.cycle function will not stop until you break the loop:
import itertools
count = 0
for c in itertools.cycle('Yang'):
if count >= 12:
break
else:
print(c, end=',')
count += 1
# Y,a,n,g,Y,a,n,g,Y,a,n,g,
itertools.count(): generate an infinite sequence of numbers
If all we need is numbers, use the itertools.count function:
import itertools
for i in itertools.count(0, 2):
if i == 20:
break
else:
print(i, end=" ")
# 0 2 4 6 8 10 12 14 16 18
As illustrated above, its first parameter is the starting number, and the second parameter is the step.