10
votes

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.

3
The next time you should add an example of the code that you can't get to work, also accept the answer that most helped you in solving the problem and up-vote the useful ones. - Rik Poggi
You're welcome, you may also want to follow some of the advice in this Style guide for questions and answers. A better question leads to better answers. - Rik Poggi

3 Answers

19
votes

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
9
votes

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.

2
votes

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

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