[Python] Can't properly modify a list in a for without It throwing error

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    I tried with [:] in lists but still doesn't work

    for bullet in self.bullets[:]:
    bullet.update(self.bullet_speed, self.bullets)
    for obstacle in game.obstacle_manager.obstacles[:]:
    if bullet.rect.colliderect(obstacle.rect):
    game.obstacle_manager.obstacles.remove(obstacle)
    self.bullets.remove(bullet)
    bullet_flag = True
    break
    if bullet_flag:
    break


    it gets the error ValueError: list.remove(x): x not in list in self.bullets.remove(bullet)

    I am looking for colision between bullets and obstacles if that happens the bullet and the obstacle should destroy

    full function

    def update(self, game):
    bullet_flag = False
    if game.player.type == WEAPON_TYPE:
    if self.bullet_step%5 == 0:
    self.bullets.append(Bullet(game.player))
    self.bullet_step += 1
    for bullet in self.bullets[:]:
    bullet.update(self.bullet_speed, self.bullets)
    for obstacle in game.obstacle_manager.obstacles[:]:
    if bullet.rect.colliderect(obstacle.rect):
    game.obstacle_manager.obstacles.remove(obstacle)
    self.bullets.remove(bullet)
    bullet_flag = True
    break
    if bullet_flag:
    break


    It seems that all answer point to use [:] so I hope you can help me since that didn't work or I'm not doing it right.
    REVIEW: in

    self.bullets.remove(bullet)


    I'm doing It in the self.bullets[:] or in the original list? I guess here is the answer.
    PS: Can't find the code.
    REVIEW2 WITH MY FATHER: So got that I was modifying the original list bullets instead the one on the for

    self.bullets[:]


    So the solution will be to create a variable before the for

    aux = self.bullets[:]


    then modify It in the for and then assigning the original to the new bullets list

    aux.remove(bullet)
    self.bullets = aux


    I honestly coulnd't think about It that's why I thought I could ask It anyway thanks everybody.
    FINAL SOLUTION:

    for bullet in aux:
    bullet.update(self.bullet_speed, self.bullets)
    for obstacle in game.obstacle_manager.obstacles[:]:
    if bullet.rect.colliderect(obstacle.rect):
    game.obstacle_manager.obstacles.remove(obstacle)
    aux.remove(bullet)
    bullet_flag = True
    break
    if bullet_flag:
    break
    self.bullets = aux

    Continue reading...

Compartilhe esta Página