Brandon Brandon - 2 years ago 160
Python Question

Looping from 1 to infinity in Python

In C, I would do this:

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

How can I achieve something similar in Python?

Answer Source

Using count from itertools

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

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):

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):

So it's probably best to use count()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download