Infinite for loops possible in Python?

后端 未结 10 2181
误落风尘
误落风尘 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: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)
    

提交回复
热议问题