Is there an expression for an infinite iterator?
for x in iter(int, 1): pass
- Two-argument
iter
= zero-argument callable + sentinel value int()
always returns0
Therefore, iter(int, 1)
is an infinite iterator. There are obviously a huge number of variations on this particular theme (especially once you add lambda
into the mix). One variant of particular note is iter(f, object())
, as using a freshly created object as the sentinel value almost guarantees an infinite iterator regardless of the callable used as the first argument.
itertools
provides three infinite iterators:
count(start=0, step=1)
: 0, 1, 2, 3, 4, ...cycle(p)
: p[0], p[1], ..., p[-1], p[0], ...repeat(x, times=∞)
: x, x, x, x, ...
I don't know of any others in the standard library.
Since you asked for a one-liner:
__import__("itertools").count()