-2

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Timur
  • 7
  • 2
  • 1
    https://stackoverflow.com/questions/920645/when-to-use-while-or-for-in-python – Johnny John Boy Jul 07 '22 at 14:58
  • 1
    This happens because you are deleting items from the array you are iterating over. Usually you don't want to do that – C_Z_ Jul 07 '22 at 15:02
  • Start debugging. This should make things clear for such a small example (Even pen & paper debugging should be sufficient for such a small example) – MrSmith42 Jul 07 '22 at 16:33

1 Answers1

1

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

syter
  • 135
  • 2
  • 10