1

In C++ we can write an infinite for loop like for(;;). Is here any syntax like this to write an infinite for loop in Python?

Note : I know that if I write for i in range(a_very_big_value) then it may run infinity. I am searching a simple syntax like C++ or any other tricks to write infinite for loop in Python.

5
  • It's a while loop, I am searching for for loop. Commented Jun 22, 2018 at 4:24
  • 1
    Why do you need a for loop? Commented Jun 22, 2018 at 4:30
  • I have C++ background, that's why I am searching for something like C++. You can say it curiosity. Commented Jun 22, 2018 at 4:31
  • If you have a C++ background, think about it this way: how would you write an infinite range for loop in C++? That's much closer to what Python's for loop is than the C-style for loop. Commented Jun 22, 2018 at 4:34
  • yeah, nice point to notice. thanks Commented Jun 22, 2018 at 4:35

6 Answers 6

4

Python's for statement is a "for-each" loop (sort of like range-for in C++11 and later), not a C-style "for-computation" loop.

But notice that in C, for (;;) does the same thing as while (1). And Python's while loop is basically the same as C's with a few extra bells and whistles. And, in fact, the idiomatic way to loop forever is:1

while True:

If you really do want to write a for loop that goes forever, you need an iterable of infinite length. You can grab one out of the standard library:2

for _ in itertools.count():

… or write one yourself:

def forever():
    while True:
        yield None

for _ in forever():

But again, this isn't really that similar to for (;;), because it's a for-each loop.


1. while 1: used to be a common alternative. It's faster in older versions of Python, although not in current ones, and occasionally that mattered.

2. Of course the point of count isn't just going on forever, it's counting up numbers forever. For example, if enumerate didn't exist, you could write it as zip(itertools.count(), it).

Sign up to request clarification or add additional context in comments.

Comments

3

Yes, it is possible.

With a while loop:

while True:
   ...

With a for loop (just for kicks):

from itertools import cycle    
for _ in cycle(range(1)):
    ...

The cycle returns 1 indefinitely.

In either case, it's up to you to implement your loop logic in such a way that you terminate eventually. And lastly, if you want to implement an execute-until-___ loop, you should stick to while True, because that's the idiomatic way of doing it.

Comments

2

I found the answer from here and here

Using itertools.count:

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

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

import sys
for i in xrange(sys.maxint):
    if there_is_a_reason_to_break(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 there_is_a_reason_to_break(i):
        break

So it's probably best to use count()


It is also possible to achieve this by mutating the list you're iterating on, for example:

l = [1]
for x in l:
    l.append(x + 1)
    print(x)

Comments

1

Yes, here you are:

for i in __import__("itertools").count():
    pass

The infinite iterator part was taken from this answer. If you really think about it though, a while loop looks way better.

while True:
    pass

Comments

0

You can use:

while True:
    # Do stuff here

1 Comment

I have asked for for loop not while loop :(
0
for _ in iter(str, "forever"):
...     pass

This may help. Because the iter() function creates an iterator that will call str() with no arguments for each call to its next() method[ This returns an empty string ]; if the value returned by str() is equal to the string "forever"(WHICH WILL NEVER HAPPEN AS "" != "forever"), StopIteration will be raised thus breaking the loop, otherwise the loop will continue running and this is the case for our loop.

REF: https://docs.python.org/3/library/functions.html?highlight=iter#iter

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.