I have this function that creates a Ball object and appends it to a list:
list_of_balls = []
def create_new_ball():
newball = Ball()
list_of_balls.append(newball)
I need to be able to remove specific instances of Ball from that list. I have no idea how to do this. I cant use list_of_balls.index() because all the instances are attached to the private variable newball. When I get the list something like this is returned:
[<main.Foo instance at 0x22149c>, <main.Foo instance at 0x22111c>, <main.Foo instance at 0x2209b4>, <main.Foo instance at 0x22129c>]
So I have no idea of how to aim specific instances.
Is there a way to remove specific instances of Ball from that list? Each Ball instance needs to be able to remove itself from the list, but how do the instance knows who it is on the list and/or what is its index?
Edit: What I need to do is to identify them on that list (or dictionary, or other alternative). I know how to remove items from a list, what I can’t figure out is how to do it specifically.
I want to do exactly what aList.remove() does, but I don’t have a variable to use as argument, so I need an alternative.
list.removeseems to work Ok:The real question is how do you know which
Ballyou want to remove?Based on the comments, it looks like you want all of the balls which have bounced N times to be removed:
Alternatively, if you don’t need to do this in place, you can create a new list with balls which haven’t bounced N times:
Finally, you can use this idiom and slice assignment to do the whole thing in place if you need to: