Incrementing a for loop, inside the loop

后端 未结 4 932
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 12:30

Is it possible to increment a for loop inside of the loop in python 3?

for example:

for i in range(0, len(foo_list)):
    if foo_list[i] < bar
            


        
4条回答
  •  走了就别回头了
    2021-01-05 13:13

    In your example as written i will be reset at each new iteration of the loop (which may seem a little counterintuitive), as seen here:

    foo_list = [1, 2, 3]
    
    for i in range(len(foo_list)):
        print('Before increment:', i)
        i += 4
        print('After increment', i)
    
    >>>
    Before increment: 0
    After increment 4
    Before increment: 1
    After increment 5
    Before increment: 2
    After increment 6
    

    continue is the standard/safe way to skip to the next single iteration of a loop, but it would be far more awkward to chain continues together than to just use a while loop as others suggested.

提交回复
热议问题