'Easy way to keep counting up infinitely

What's a good way to keep counting up infinitely? I'm trying to write a condition that will keep going until there's no value in a database, so it's going to iterate from 0, up to theoretically infinity (inside a try block, of course).

How would I count upwards infinitely? Or should I use something else?

I am looking for something similar to i++ in other languages, where it keeps iterating until failure.



Solution 1:[1]

Take a look at itertools.count().

From the docs:

count(start=0, step=1) --> count object

Make an iterator that returns evenly spaced values starting with n. Equivalent to:

def count(start=0, step=1):
    # count(10) --> 10 11 12 13 14 ...
    # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
    n = start
    while True:
        yield n
        n += step

So for example:

import itertools

for i in itertools.count(13):
   print(i)

would generate an infinite sequence starting with 13, in steps of +1. And, I hadn't tried this before, but you can count down too of course:

for i in itertools.count(100, -5):
    print(i)

starts at 100, and keeps subtracting 5 for each new value ....


Solution 2:[2]

This is a bit smaller code than what the other user provided!

x = 1
while True:
    x = x+1
    print x

Solution 3:[3]

A little shorter, using an iterator and no library:

x = 0
for x in iter(lambda: x+1, -1):
    print(x)

But it requires a variable in the current scope.

Solution 4:[4]

this easier using no library and i got it from the upper code but there was an issue that , in the print line he just added print x

x = 1
while True:
   x = x+1
   print (f'{x}')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jamylak
Solution 2 Nic
Solution 3 Eric
Solution 4 V E X