Home > Back-end >  how does "for" loop works python?
how does "for" loop works python?

Time:07-08

Why does it happen, that on four while-iteration "for loop" iterates only 2 times, while the array length is 3

import time
array = [[1, 1, 3], [2, 2, 3], [3, 3, 3]]

while True:
    #print (array)
    time.sleep(1)
    index = 0
    print (array)
    for proxy in array:
        
        print("iteration")
        if proxy[2] == 0:
            del array[index]
            continue
        
        proxy[2] -= 1
        index  = 1
    print ("\n")

Compile

CodePudding user response:

When the last item of any of the arrays turns 0 (which happens after a few turns), you have the item deleted. This makes there only be 2 items instead of 3, and the for loop runs over those items, so it only iterates twice.

Edit::one good solution is to make a copy of the array, so that you can use one to delete items from, and one to iterate (loop) through

  • Related