Kos Kos - 8 months ago 32
Python Question

How to delete an object from a list inside a list?

Let's say there are three lists, the third being a list containing the first two:

Friendly_List = list()
Enemy_List = list()
Battle_Space = list([Friendly_List, Enemy_List])

And a goblin class:

class Goblin(object):
def __init__(self):
self.Name = "Goblin"
self.HP = random.randint(15,20)
self.Damage = random.randint(5,10)

I create an instance of the Goblin class:

x = Goblin()

Then put it into Friendly_List:


Now let's say the goblin dies heroically and must be removed from the battlefield. If I do Friendly_List.remove(x), the goblin is removed without issue.

If I do Battle_Space.remove(x), it says that x is not in the list - even though x is in one of the lists that is part of the Battle_Space list.

I guess what I'm trying to ask really is: what is the proper way to achieve the desired behavior of Battle_Space.remove(x)? To remove an instance that is a layer deep?


The simple but maybe not-so-clean way is Battle_Space[0].remove(x). You would have to ensure that the first list is the friendly list.

My suggestion for readability would be to consider putting friendly_list and enemy_list in a BattleSpace object so you can refer to them by name. You can also create a method in that object to remove a target from any child list:

class BattleSpace(object):
    def __init__(self):
        self.friendly_list = []
        self.enemy_list = []

    def remove(self, target):
        if target in self.friendly_list:
        if target in self.enemy_list:

battle_space = BattleSpace()
battle_space.remove(x)  # can also do battle_space.friendly_list.remove(x)

Edit: Just read the OP's comment that the desire is to remove anywhere in the list. Modified code.