Infinite for loops possible in Python?

后端 未结 10 2174
误落风尘
误落风尘 2020-12-06 10:39

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

My guess is that there can be an infinite for loop in Python. I\'d like to know this for future refe

相关标签:
10条回答
  • 2020-12-06 11:34

    Here's another solution using the itertools module.

    import itertools
    
    for _ in itertools.repeat([]):  # return an infinite iterator
        pass
    
    0 讨论(0)
  • 2020-12-06 11:36

    To answer your question using a for loop as requested, this would loop forever as 1 will never be equal to 0:

    for _ in iter(int, 1):
        pass
    

    If you wanted an infinite loop using numbers that were incrementing as per the first answer you could use itertools.count:

    from itertools import count
    
    for i in count(0):
        ....
    
    0 讨论(0)
  • 2020-12-06 11:42

    Yes, use a generator that always yields another 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)
    

    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)
    
    0 讨论(0)
  • 2020-12-06 11:42

    You can configure it to use a list. And append an element to the list everytime you iterate, so that it never ends.

    Example:

    list=[0]
    t=1
    for i in list:
            list.append(i)
            #do your thing.
            #Example code.
            if t<=0:
                    break
            print(t)
            t=t/10
    

    This exact loop given above, won't get to infinity. But you can edit the if statement to get infinite for loop.

    I know this may create some memory issues, but this is the best that I could come up with.

    0 讨论(0)
提交回复
热议问题