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)
7
  • @Aurora0001 It's not a duplicate of that question as I would like no usage of while-loops Commented Aug 24, 2016 at 12:39
  • 1
    The accepted answer of that question uses no while loops, so it's exactly what you want, yes? If not, why not? Commented Aug 24, 2016 at 12:42
  • @Kevin My bad I only checked the question. But yeah that would count as a solution. Commented Aug 24, 2016 at 12:45
  • Yeah somehow I missed the proposed duplicate and drafted an answer that was exactly identical with the accepted answer in that other question... Commented Aug 24, 2016 at 13:27
  • @Antti Haapala Does this realy count as a duplicate ? I feel like they are two different questions that append to have common answers. Commented Aug 24, 2016 at 13:33

4 Answers 4

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

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

3 Comments

this solution is simple and pleasant to the eyes, +1
@Lost Many thanks!
@AnttiHaapala Thanks for the correct comment. For Python3, next should be replaced with __next__ (updated in the question).
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.

Comments

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.

8 Comments

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.
The doc for itertools.repeat indicate that it is roughly equivalent to a function containing a while
@jadsq The source for repeat has no use of while whatsoever.
@AmiTavory See edit
@RoadieRich Oh, good answer, then (in a completely different direction).
|
-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

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.