Currently, to iterate over finite arithmetic sequences of integers, range
is used, as in:
for i in range(10):
print(i)
For an infinite arithmetic sequence, there are a few approaches. One can replace the ‘10’ with a long sequence of nines, write a generator function or just switch to a while loop, but the current ‘best’ way is using itertools:
import itertools
for i in itertools.count():
print(i)
There are a few downsides to this. Firstly, itertools.count
is doing a very similar thing to range
, yet seems on first glance completely unrelated. Without knowing, it’s easy to assume that itertools.count
does a similar thing to list.count
or str.count
, rather than range
.
In some other languages the finite and infinite cases look very similar, C (and other languages with the same loop syntax) and Rust being two examples.
Secondly, infinite loops like this are quite common in tiny example programs, e.g.
import itertools
primes = []
for i in itertools.count(2):
if all(i % p for p in primes):
primes.append(i)
print(i)
In these cases, having to import itertools to get an infinite loop makes the program significantly longer.
I propose using range(start, None, step)
for an endless range. This makes sense, as the ‘stop’ parameter is None, i.e. there is no ‘stop’ and the iterable goes on forever. The step
and start
parameters could be omitted as normal.
I would also suggest range()
should default to an end of None
with zero arguments:
for i in range():
print(i)
Downsides:
- Performance hit (probably tiny) on finite loops
-
len
of a range is no longer always nice - More ways to do the same thing (perhaps deprecate
itertools.count
?)