OOP python - removing an instance of a class from a list

I have a list where I save objects created by a specific class.

I would like to know, because I cannot solve this problem, how to remove an instance of a class from the list?

This should happen based on knowledge of one attribute of the object.

+5
source share
3 answers

Go through the list, find the object and its position, and then delete it:

for i, o in enumerate(obj_list):
    if o.attr == known_value:
        del obj_list[i]
        break
+11
source

You can use list comprehension:

thelist = [item for item in thelist if item.attribute != somevalue]

This will remove all elements with item.attribute == somevalue.

If you want to remove only one such item, use the WolframH solution .

+3
source

dict

di = {"test" : my_instance()}
del di['test']
+1

All Articles