I'm having trouble removing objects from a list. It seems that when I remove single objects in a loop, the loop kind of skips elements in the list, not continuing from the point where the last removal occurred. I want to remove only certain elements from a list, and there should be a way for an object of the list to remove itself, or mark itself for removal.
class FooObj: def __init__(self, i, a): self.i = i self.a = a def rem(self, list): #Doesn't work correctly list.remove(self) def __repr__(self): return "(obj " + str(self.i) + ", active = " + str(self.a) + ")" if __name__ == "__main__": o1 = FooObj(1, 1) o2 = FooObj(2, 0) o3 = FooObj(3, 0) o4 = FooObj(4, 1) o5 = FooObj(5, 1) #Test 1 lst = [o1, o2, o3, o4, o5] #Trying to remove objects flagged as inactive (a = 0) for obj in lst: if obj.a == 0: lst.remove(obj) #Prints: [(obj 1, active = 1), (obj 3, active = 0), (obj 4, active = 1), (obj 5, active = 1)] #^obj 3 is wrong! All objs with a=0 should be removed. print lst #Test 2 lst = [o1, o2, o3, o4, o5] #Trying to remove all objects. I need to be able to call a function of the object for each object in the loop. for obj in lst: obj.rem(lst) #Prints: [(obj 2, active = 0), (obj 4, active = 1)] #completely wrong print lst