ALAN
ALAN

Reputation: 41

Infinite loop using a for loop python

So I'm trying to make a infinite loop that uses a for loop instead of a while loop. This is my current code. If this code works it should produce x infinitely. Current code:

z=1
for x in range(0,z):
    print(x)
    z=z+1

Upvotes: 0

Views: 163

Answers (3)

bashrc
bashrc

Reputation: 4835

range returns an iterator. The iterator is already generated and evaluated before the loop iteration. (It's the returned iterator on which the loop is iterating).

The value of z is not used after the iterator is returned hence incrementing or changing its value is no-op.

If you really want an infinite loop using for you will have to write your custom generator.

For eg:

def InfiniteLoop():
   yield  1

To be used as :

for i in InfiniteLoop()

Upvotes: 2

Artier
Artier

Reputation: 1673

Update list after each iteration make infinite loop

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

Upvotes: 1

javidcf
javidcf

Reputation: 59701

That doesn't work because the first time you enter the for loop the range function generates a range from zero to the value of z at that point, and later changes to z does not affect it. You can do something like what you want using, for example, itertools.count:

from itertools import count

for x in count():
    print(x)

Upvotes: 5

Related Questions