There are multiple questions here asking about infinite range
that all recommend itertools.count
. However, range
has one ability that count
does not—it can be reused.
a = range(100)
# Prints 0 1 2 3
for i in a:
print(i)
if i >= 3:
break
# Prints 0 1 2 3
for i in a:
print(i)
if i >= 3:
break
from itertools import count
b = count(0)
# Prints 0 1 2 3
for i in b:
print(i)
if i >= 3:
break
# Prints 4, does not use a fresh count(0)
for i in b:
print(i)
if i >= 3:
break
Is there a way to reuse itertools.count
or otherwise get a reusuable/restarting infinite iterable?