10

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.

Steven Matthews
  • 9,705
  • 45
  • 126
  • 232
  • Also, why doesn't Python have i++? Literally every other language I've worked in does, and it seems like a glaring hole. – Steven Matthews Jul 11 '12 at 02:49
  • 8
    1) `i++` is syntactic sugar and I doubt that you can call it's exclusion a "glaring hole". 2) Python uses `i += 1` because it is more explicit about the increment. 3) Guido decided it was so. – Joel Cornett Jul 11 '12 at 02:51
  • 2
    i+=1 is only one more character –  Jul 11 '12 at 02:51
  • 4
    @AndrewAlexander *"There should be one-- and preferably only one --obvious way to do it."* – jamylak Jul 11 '12 at 02:53

4 Answers4

28

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 ....


jamylak
  • 128,818
  • 30
  • 231
  • 230
Levon
  • 138,105
  • 33
  • 200
  • 191
3

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

x = 1
while True:
    x = x+1
    print x
Nic
  • 12,220
  • 20
  • 77
  • 105
paebak
  • 39
  • 1
  • 1
    I like `count` but this is also valid and can come in handy if you need multiple counters. Would update to `x += 1` – CasualDemon Oct 05 '17 at 21:04
0

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.

Eric
  • 1,138
  • 11
  • 24
0

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}')
V E X
  • 45
  • 9