Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 661
Bogdan Maier Avatar asked Feb 04 '12 12:02

Bogdan Maier


2 Answers

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.

like image 159
unutbu Avatar answered Oct 17 '22 06:10

unutbu


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
like image 21
Reinstate Monica Avatar answered Oct 17 '22 06:10

Reinstate Monica