Infinite for loops possible in Python?

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

    n = 0
    li = [0]
    for i in li:
        n += 1
        li.append(n)
        print(li)
    

    In the above code, we iterate over the list (li).

    • So in the 1st iteration, i = 0 and the code in for block will run, that is li will have a new item (n+1) at index 1 in this iteration so our list becomes [ 0, 1 ]
    • Now in 2nd iteration, i = 1 and new item is appended to the li (n+1), so the li becomes [0, 1, 2]
    • In 3rd iteration, i = 2, n+1 will be appended again to the li, so the li becomes [ 0, 1, 2, 3 ]

    This will keep on going as in each iteration the size of list is increasing.

提交回复
热议问题