pythonloops

Looping from 1 to infinity in Python


In C, I would do this:

int i;
for (i = 0;; i++)
  if (thereIsAReasonToBreak(i))
    break;

How can I achieve something similar in Python?


Solution

  • Using itertools.count:

    import itertools
    for i in itertools.count(start=1):
        if there_is_a_reason_to_break(i):
            break
    

    In Python 2, range() and xrange() were limited to sys.maxsize. In Python 3 range() can go much higher, though not to infinity:

    import sys
    for i in range(sys.maxsize**10):  # you could go even higher if you really want
        if there_is_a_reason_to_break(i):
            break
    

    So it's probably best to use count().