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.
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.
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]