Infinite for loops possible in Python?

Britni.M picture Britni.M · Dec 13, 2015 · Viewed 35.3k times · Source

Is it possible to get an infinite loop in for loop?

My guess is that there can be an infinite for loop in Python. I'd like to know this for future references.

Answer

orokusaki picture orokusaki · Dec 13, 2015

The quintessential example of an infinite loop in Python is:

while True:
    pass

To apply this to a for loop, use a generator (simplest form):

def infinity():
    while True:
        yield

This can be used as follows:

for _ in infinity():
    pass