Learn Web Development with Python
上QQ阅读APP看书,第一时间看更新

Infinite iterators

Infinite iterators allow you to work with a for loop in a different fashion, such as if it were a while loop:

# infinite.py
from itertools import count

for n in count(5, 3):
if n > 20:
break
print(n, end=', ') # instead of newline, comma and space

Running the code gives this:

$ python infinite.py
5, 8, 11, 14, 17, 20,

The count factory class makes an iterator that just goes on and on counting. It starts from 5 and keeps adding 3 to it. We need to break it manually if we don't want to get stuck in an infinite loop.