Brandon Brandon - 7 months ago 17
Python Question

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?

Answer

Using count from itertools

import itertools
for i in itertools.count():
  if thereIsAReasonToBreak(i):
    break

In Python2 xrange() is limited to sys.maxint, which may be enough for most practical purposes

import sys
for i in range(sys.maxint):
  if thereIsAReasonToBreak(i):
    break

In Python3, 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 thereIsAReasonToBreak(i):
    break

So it's probably best to use count()

Comments