Bogdan Maier
Bogdan Maier

Reputation: 683

OOP python - removing class instance from a list

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

I would like to know, cause I can't manage to solve this issue, how do I delete an instance of the class from the list?

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

Upvotes: 13

Views: 28548

Answers (3)

Reinstate Monica
Reinstate Monica

Reputation: 4723

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

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

Upvotes: 22

Jakob Bowyer
Jakob Bowyer

Reputation: 34708

You could have stored them in a dict and removed them by name

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

Upvotes: 2

unutbu
unutbu

Reputation: 881007

You could use a list comprehension:

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

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

If you wish to remove just one such item, then use WolframH's solution.

Upvotes: 13

Related Questions