0

I have a list of objects. The list contains Players, each Player has 3 attributes. player_name, player_number, and player position. I want to search through the list by player_name, find the first instance of that object and remove the object.

p1 = Player("Pete", "12", "runner")
p2 = Player("John", "5", "catcher")
p3 = Player("John", "29", "guard")
player.list = [p1, p2, p3]

I want to remove the first instance of john, which would be p2

I can search through the list and find him but im lost on how to remove the whole object of him. I want to use .remove() somehow since i know it works on the first time it sees it but i cant figure it out.

for i in player.list:
    if i.player_name == "John":
        player.list.remove(i)

The issue with my approach is its removing all of them because its looping through the whole list. what would be a better way to search this list, maybe add a counter or something?

C89
  • 21
  • 3

4 Answers4

1

Just form a new list:

players = [item
           for item in player.list 
           if not item.player_name == "John"]
Jan
  • 42,290
  • 8
  • 54
  • 79
1
for i in player.list:
    if i.player_name == "John":
        player.list.remove(i)
        break
MeBex
  • 488
  • 1
  • 5
  • 20
1

Here's a simple solution: find the player, if any, and remove it if found.

if any((to_go:= p).player_name == "John" for p in player.list):
    player.list.remove(to_go)

any(p.player_name == "John" for p in player.list) returns True if any player in the list has the name John, with iteration stopping as soon as possible. If no such player exists, it returns False.

The assignment expression in Python 3.8 lets you capture the "witness" to the fact that a player exists with the name John, namely the player object itself.

Inside the if statement, we just pass to_go to player.list.remove to remove the last player bound to to_go before any exited. We only call remove if any returns True; otherwise, we would incorrectly remove the last player in the list if nobody's name was John.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

This post should help you:

How to remove items from a list while iterating?

Just put a condition in your determine that stops removal after 1 has been removed?

James
  • 332
  • 2
  • 3
  • 9