Changing the value of range during iteration in Python

前端 未结 3 1212
深忆病人
深忆病人 2020-12-12 00:24
>>> k = 8
>>> for i in range(k):
        print i
        k -= 3
        print k

Above the is the code which prints numbers from <

3条回答
  •  情书的邮戳
    2020-12-12 00:54

    If you do want to change k and affect the loop you need to make sure you are iterating over mutable object. For example:

    k = list(range(8))
    for i in k:
            print(i)
            k.pop()
            k.pop()
            k.pop()
            print(k)
    

    Or alternatively:

    k = list(range(8))
    for i in k:
            print(i)
            k[:] = k[:-3]
            print(k)
    

    Both will result with

    0
    [0, 1, 2, 3, 4]
    1
    [0, 1]
    

提交回复
热议问题