Usually in Python we can avoid the i = 0 … i += 1 paradigm that we use in other languages when we need to count things, thanks to enumerate(...), for i in range(100), etc.
Along the years I have nearly always found a more “pythonic” replacement for code containing i = 0 … i += 1.
There is an exception with this code: an infinite loop with a counter:
i = 0
i += 1
Proposal: could we accept that range() without any parameter gives an infinite iteration?
for i in range(): # infinite loop
Basically range() without parameter would have the same behaviour than:
for i in itertools.count():
Have you considered making this available directly, without any import, with range()?
And since we don’t have a “start” argument, it never starts, right?
Jokes aside, you would need to define len(range()), reversed(range()), range()[-1], range()[::-1], x in range(). And you would see that range() is a very special object, different from ordinary range object in many ways. So why call it range() and not count()? I am sure that this option was already discussed when the itertools module was added, and there were reasons of adding itertools.count().
Not having a start value would be a non-starter (pun not intended). It would have fewer features than itertools.count(). I can see maybe doing something that has more features, but not the same or fewer.
It was just an idea because I often see people doing i = 0; while True: ... i += 1 in code, and there seemed to be an improvement “for free” with a range with no stop: range() or range(start=100).
But anyway, not a big deal.
Thanks for starting this thread. It just so happens that yesterday I wrote a i = 0; while True: ... i += 1 loop, and today I changed it to a for i in itertools.count() loop. Definitely an improvement, and one I wouldn’t have made without this thread.
Haha, happy for this
This is a good sign that we shouldn’t have to import anything to do this (in the same way we don’t import anything to enumerate), and that for i in range() would be perfect, but I promiss I stop now haha! (we can close this thread).
Serhiy’s comment here is the key conceptual reason unbounded ranges aren’t allowed: they’re defined as memory efficient computed sequences rather than consumable iterators, so they’re expected to have a lower and upper bound, even though those limits might be large.
That said, there are already some range operations that throw an exception if the sequence length doesn’t fit in 64 bits, so it isn’t unthinkable to have a special case for “stop=None”. However, unlike the “computed sequence that wouldn’t fit in a 64 bit address space” case, the unbounded sequence case would either slow down multiple operations with extra checks for None, or else we’d have to play constructor games to return a different object type for the special case (and such games are inevitably confusing to maintain).
By contrast, “from itertools import count” is simple to understand conceptually and straightforward to maintain.