13

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.

Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
Bogdan Maier
  • 663
  • 2
  • 13
  • 19
  • 1
    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 Feb 04 '12 at 13:20
  • You're welcome, you may also want to follow some of the advice in this [Style guide for questions and answers](http://meta.stackexchange.com/a/18616/177799). A better question leads to better answers. – Rik Poggi Feb 04 '12 at 18:48

3 Answers3

21

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
Reinstate Monica
  • 4,568
  • 1
  • 24
  • 35
  • This works great if it's only one element you need to remove, otherwise @unutbu's answer works. – Devyzr Sep 20 '21 at 19:22
12

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.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • A filter would work like the list comprehension, but typically calling `filter` is slower than a list comprehension. – unutbu Feb 04 '12 at 12:50
  • Hey man can you be my mentor on Python? I won't disturb you too much I promise. – Alexander Aug 05 '23 at 21:08
2

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

di = {"test" : my_instance()}
del di['test']
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91