Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite for loops possible in Python?

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.

like image 405
Britni.M Avatar asked Dec 13 '15 17:12

Britni.M


People also ask

Is an infinite for loop possible?

A for loop is only another syntax for a while loop. Everything which is possible with one of them is also possible with the other one. Any for loop where the termination condition can never be met will be infinite: for($i = 0; $i > -1; $i++) { ... }

How do you run an infinite time loop in Python?

Infinite While Loop in Pythona = 1 while a==1: b = input(“what's your name?”) print(“Hi”, b, “, Welcome to Intellipaat!”) If we run the above code block, it will execute an infinite loop that will ask for our names again and again. The loop won't break until we press 'Ctrl+C'.


2 Answers

You can use the second argument of iter(), to call a function repeatedly until its return value matches that argument. This would loop forever as 1 will never be equal to 0 (which is the return value of int()):

for _ in iter(int, 1):     pass 

If you wanted an infinite loop using numbers that are incrementing you could use itertools.count:

from itertools import count  for i in count(0):     .... 
like image 181
Padraic Cunningham Avatar answered Sep 23 '22 06:09

Padraic Cunningham


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 
like image 27
orokusaki Avatar answered Sep 24 '22 06:09

orokusaki