-1

Im creating a game where i have roads that move down and when the y is 0, i add another image on top of it, i tried to detect whether the image if off of the screen and remove it from the list, just so the list doesnt contain a billion characters. My code:

for i in range(len(lanes_y)):
        #increases the y of every image
        lanes_y[i] += 1
        #if the y is 0 we add a new image on top of the image
        if lanes_y[i] == 0:
            lanes_y.append(lanes_y[i] - 500)
        #if one of the images is less then 500 i remove it from the list to reduce lag
        if lanes_y[i] >= 500:
            lanes_y.pop(i)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Morris
  • 55
  • 6

2 Answers2

0

what is happening you are changing your list in the middle of execution with the command lanes_y.pop(i) there for the length of the list changes in runtime:

l = [1,2,3,4]

for i in range(len(l)):
    if i ==2:
        l.pop(i)
     print(len(l))

the output will be:

4
4
3
3

so in the final iteration when you are pointing at index 3 id dosent exist anymore.

Elad L.
  • 629
  • 1
  • 10
  • 25
0

It is advised not to change the list while iterating over it.

However, you can remove or add elements, but you will have to update the value loop variable i accordingly:

lst = [i*i for i in range(5)]
# lst is [0, 1, 4, 9, 16]

for i in range(len(lst)):
  if i == 3:    
    lst.remove(9)
    # now lst becomes [0, 1, 4, 16]
    # so the index of next element is 3.
    # but the for loop will auto increment the i
    i -= 1    # it will cancel the effect of increment

  # do something with the lst[i]
  print(lst[i])