0

Im trying to make a system where I use a list to store my enemy data, then i run through that data with a For-loop and update it, but when i do this the for loop ends up running more then once on a single item in the list.

def enemyupdate():
for e in enemylist:
    innerlist = e
    side = innerlist[0]
    e_rect = list(innerlist[1])
    if side == 0:
        e_rect[0]+=2
    if side == 1:
        e_rect[0]-=2
    enemylist.remove(e)
    if player.colliderect(tuple(pg.Rect(e_rect))) != True:
        enemylist.append([side,tuple(e_rect)])
    print(e)

but the out put comes out as:

[0, (4546, 215, 20, 100)]
[0, (4548, 215, 20, 100)]
[0, (2298, 236, 20, 100)]
[0, (4550, 215, 20, 100)]
[0, (4552, 215, 20, 100)]
[0, (2490, 44, 20, 100)]
[0, (4554, 215, 20, 100)]
[0, (4556, 215, 20, 100)]
[0, (2300, 236, 20, 100)]
[0, (4558, 215, 20, 100)]
[0, (4560, 215, 20, 100)]
[0, (2492, 44, 20, 100)]
[0, (4562, 215, 20, 100)]
[0, (4564, 215, 20, 100)]
[0, (2302, 236, 20, 100)]
[0, (4566, 215, 20, 100)]
[0, (4568, 215, 20, 100)]
[0, (2494, 44, 20, 100)]
[0, (4570, 215, 20, 100)]
[0, (4572, 215, 20, 100)]
[0, (2304, 236, 20, 100)]
[0, (4574, 215, 20, 100)]
[0, (4576, 215, 20, 100)]
[0, (2496, 44, 20, 100)]
[0, (4578, 215, 20, 100)]
[0, (4580, 215, 20, 100)]
[0, (2306, 236, 20, 100)]
[0, (4582, 215, 20, 100)]
[0, (4584, 215, 20, 100)]
[0, (2498, 44, 20, 100)]
[0, (4586, 215, 20, 100)]
[0, (4588, 215, 20, 100)]
[0, (2308, 236, 20, 100)]
[0, (4590, 215, 20, 100)]
[0, (4592, 215, 20, 100)]
[0, (2500, 44, 20, 100)]
[0, (4594, 215, 20, 100)]
[0, (4596, 215, 20, 100)]
[0, (2310, 236, 20, 100)]
[0, (4598, 215, 20, 100)]
[0, (4600, 215, 20, 100)]
[0, (2502, 44, 20, 100)]
[0, (4602, 215, 20, 100)]
[0, (4604, 215, 20, 100)]

The second number in the tuple never changes so you can see how some items are getting repeated.

why is this happening?

  • 4
    Can you provide a minimal input dataset, the matching expected output and a brief description of the logic? Also you're modifying the list while iterating over it, this is a non working approach. – mozway Apr 10 '22 at 05:41
  • About iterate/modify, see for example https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it . – Ture Pålsson Apr 10 '22 at 06:01
  • Thank you, I understand how that wont work. :) – Jermoes Apr 10 '22 at 06:22

0 Answers0