Endlessly for loops in Python?

Is it possible to get an infinite loop in a loop for?

I assume that in Python there can be an infinite for loop. I would like to know this for future reference.

+4
source share
4 answers

Yes, use a generator that always gives a different number: Here is an example

def zero_to_infinity():
    i = 0
    while True:
        yield i
        i += 1

for x in zero_to_infinity():
    print(x)

This can also be achieved by changing the list that you are running, for example:

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

A quintessential example of an infinite loop in Python:

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
+4
source

, for , , 1 0:

for _ in iter(int, 1):
    pass

, , itertools.count:

from itertools import count

for i in count(0):
    ....
+1

, , , ( , ...)

A Python . , :

for element in iterable:
    foo(element)

:

iterator = iterable.__iter__()
try:
    while True:
        element = iterator.next()
        foo(element)
except StopIteration:
    pass

, , next, ( , StopIteration).

Thus, each iterative object from which the nextiterator method never raises the mentioned exception has an infinite loop. For example:

class InfLoopIter(object):
    def __iter__(self):
        return self # an iterator object must always have this
    def next(self):
        return None

class InfLoop(object):
    def __iter__(self):
        return InfLoopIter()

for i in InfLoop():
    print "Hello World!" # infinite loop yay!
0
source

Source: https://habr.com/ru/post/1619726/


All Articles