Changing the value of range during iteration in Python

前端 未结 3 1181
深忆病人
深忆病人 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]
    
    0 讨论(0)
  • 2020-12-12 00:59

    The expression range(k) is evaluated just once, not on every iteration. You can't set k and expect the range(k) result to change, no. From the for statement documentation:

    The expression list is evaluated once; it should yield an iterable object.

    You can use a while loop instead:

    i = 0
    k = 8
    while i < k:
        print i
        i += 1
        k -= 3
    

    A while loop does re-evaluate the test each iteration. Referencing the while statement documentation:

    This repeatedly tests the expression and, if it is true, executes the first suite

    0 讨论(0)
  • 2020-12-12 01:08

    You can't change the range after it's been generated. In Python 2, range(k) will make a list of integers from 0 to k, like this: [0, 1, 2, 3, 4, 5, 6, 7]. Changing k after the list has been made will do nothing.

    If you want to change the number to iterate to, you could use a while loop, like this:

    k = 8
    i = 0
    while i < k:
        print i
        k -= 3
        i += 1
    
    0 讨论(0)
提交回复
热议问题