Is it possible to delete an instance of a class that automatically removes it from all lists in which it is an element?
class, del, instance, list, python
Solution
One answer to this is to always allow the objects that you are putting into the lists to manage list membership. For example, rather than saying
listA.append(objectA)
you would use
objectA.addToList(listA)
This would allow you to internally store a list of all list that contain `objectA`. Then, when you want to delete `objectA`, you need to call a method like this:
def cleanup(self):
for listToClean in myLists:
listToClean.remove(self)
This does put some strong limitations on your program though - for example, if a copy is made of one of these lists, then the objects will not have a reference to that copy. You have to work with the assumption that any copy of a list (don't forget that slices are copies, too) may have obsolete objects in it, which would mean that you would want to be working with the original lists as frequently as possible.
Problem
I have an instance of a `class` which appears as an element in multiple `list`s. I want to delete the instance and simultaneously remove it from every `list` in which it is an element. Is this possible?