December 2018
Beginner to intermediate
796 pages
19h 54m
English
Infinite iterators allow you to work with a for loop in a different fashion, such as if it were a while loop:
# infinite.pyfrom itertools import countfor 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.
Read now
Unlock full access