Search code examples
pythonlistfor-loopinstances

delete list of instance from iteratively created list of instances


I have created a list of instances (with a for loop). When I try to delete single instances from this list I get an error saying they aren't in the list. I have made a simple example showing my problem:

class example ():
    list = []

    def __init__ (self, name):
        example.list.append(self)
        self.name = name

for i in range(5):
    name = ("example_" + str(i+1))
    name = example(name)

to_delete = []

to_delete.append(example.list[2])
to_delete.append(example.list[0])
to_delete.append(example.list[4])

for j in to_delete:
    example.list.remove(to_delete)

print(example.list)

The objects to delete are in the list. At least, when I print them out:

List of instances:
[<__main__.example object at 0x7fdc77082c50>, <__main__.example object at 0x7fdc77082be0>, <__main__.example object at 0x7fdc77082c88>, <__main__.example object at 0x7fdc77082b00>, <__main__.example object at 0x7fdc77082b38>]

Objects to remove:
[<__main__.example object at 0x7fdc77082c88>, <__main__.example object at 0x7fdc77082c50>, <__main__.example object at 0x7fdc77082b38>]

Why is this behaving oddly?


Solution

  • You are trying to remove the whole list to_delete from the list, not each item individually. As the object to_delete itself is not in the list (though each item it contains is), it will throw an error.

    This:

    for j in to_delete:
        example.list.remove(to_delete) #try to remove object to_delete
    

    Should be:

    for j in to_delete:
        example.list.remove(j) #try to remove each object IN to_delete
    

    Additionally, you could simply use list comprehension to do this:

    example.list = [x for x in example.list if x not in to_delete]