2

Having started to learn code with C, I had always assumed that for-loops and while-loops where essentialy always equivalent (as in one could always reproduce the behaviour of one using only the other). But in python while going from a for-loop to a while-loop is always trivial, I could not find a way to achieve the reverse.

Is there any way, in python, to reproduce the behaviour of a while-loop (infinite looping) using only for-loops ?

Here is a solution that doesn't work (because of the recursion limit) using a recursive generator:

def infinite_loopy():
    yield "All work and no play makes Jack a dull boy"
    for x in infinite_loopy():
        yield x

#here starts the supposedly infinite-loop
for x in infinite_loopy():
    print(x)
jadsq
  • 3,033
  • 3
  • 20
  • 32

4 Answers4

5

You can do this by writing a non-yield iterator class:

class Infinite(object):
    def __iter__(self):
        return self

    def next(self): # For Python3, replace this with __next__
        return 1

# Loops forever
for i in Infinite():
    pass

(You can see it stalling on ideone if you have the patience - it's like watching paint dry).

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
5

You can use the two-argument version of iter as follows:

for _ in iter(int, 1):
    print('All your loops are belong to us!')

The 2-argument form of iter calls the first argument as a function with no arguments. If the returned value equals (==) the second argument, StopIteration is raised, otherwise the return value is yielded. int() called without arguments returns 0 which is of course not equal to 1 thus yielding 0 forever, and we have an infinite loop.

4

You can use itertools.repeat, count or cycle:

import itertools

for _ in itertools.repeat(None):
    # infinite loop

for _ in itertools.count():
    # infinite loop

for _ in itertools.cycle([None]):
    # infinite loop

All of these can be represented by functions using while loops, but the itertools module is implemented in c (in cPython), and makes no use of while loops in the source code. Similarly for jython (java), and even PyPy (python). The same is true for count and cycle.

RoadieRich
  • 6,330
  • 3
  • 35
  • 52
  • 1
    It's still possible that they're internally implemented using a `while`, no? I think that's how the OP responded to Aurora's comment just under the question. – Ami Tavory Aug 24 '16 at 12:46
  • The [doc](https://docs.python.org/2/library/itertools.html#itertools.repeat) for itertools.repeat indicate that it is roughly equivalent to a function containing a `while` – jadsq Aug 24 '16 at 12:48
  • @jadsq The [source for `repeat`](https://github.com/python/cpython/blob/master/Modules/itertoolsmodule.c#L4119) has no use of `while` whatsoever. – RoadieRich Aug 24 '16 at 12:56
  • @AmiTavory See edit – RoadieRich Aug 24 '16 at 13:06
  • @RoadieRich Oh, good answer, then (in a completely different direction). – Ami Tavory Aug 24 '16 at 13:07
  • @RoadieRich Alrigth then, its not extremely idomatic but its fair enough. – jadsq Aug 24 '16 at 13:10
  • @jadsq you don't get much more idiomatic than using the standard library for what it's designed for. – RoadieRich Aug 24 '16 at 13:13
  • @RoadieRich That's true. I just meant it as in "bare bones" python. – jadsq Aug 24 '16 at 13:28
-1

You can use itertools.count() in for loop.

import itertools

def infinite_loopy():
    x = "All work and no play makes Jack a dull boy"
    for x in itertools.count():
        yield x

for i in infinite_loopy():
    print("All work and no play makes Jack a dull boy")

[Reference] Looping from 1 to infinity in Python

Community
  • 1
  • 1
Daewon Lee
  • 620
  • 4
  • 6