-2
class MyClass():
    def __init__(self, name, att1, att2):
        ...

myList = [MyClass("p1", 1, 1), MyClass("p2", 0, 0), MyClass("p3", 0, 1)]

Now I want to remove every object from myList if its att2 == 1.

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
  • You will need to know the instance variable name associated with att2 – DarkKnight Jun 15 '22 at 10:54
  • Does this answer your question? [remove item from list according to item's special attribute](https://stackoverflow.com/questions/33995906/remove-item-from-list-according-to-items-special-attribute) – buran Jun 15 '22 at 10:57

1 Answers1

1

Rather than removing the class instance from the list, construct a new list (list comprehension) that excludes unwanted classes. For example:

class MyClass():
    def __init__(self, name, att1, att2):
        self._name = name
        self._att1 = att1
        self._att2 = att2
    def __repr__(self):
        return f'{self._name=}, {self._att1=}, {self._att2=}'

myList = [MyClass("p1", 1, 1), MyClass("p2", 0, 0), MyClass("p3", 0, 1)]

myList = [c for c in myList if c._att2 != 1]

print(myList)

Output:

[self._name='p2', self._att1=0, self._att2=0]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Nice usage of the `=` format specifier! That being said, I think the `__repr__` implementation adds multiple additional concepts that might be confusing for beginners. – fsimonjetz Jun 15 '22 at 11:12
  • @fsimonjetz Force of habit. I **always** add a repr to any class that I devise and I would recommend that everyone does so as a matter of course. But that's my opinion which is not held in high esteem by the usual pedants in this forum – DarkKnight Jun 15 '22 at 11:15