I'm struggling to see how you got a KeyError for this, unless you're doing something exotic ( in which case I'll need more code ).
Anyway, instead looping through a list and remove elements in the for loop, you should instead try one of the below:
- Loop through a copy of the list of bubbles, removing from them from the original list ( for bubble1 in bubbles[:]: )
- Loop through the list using an iterator ( for bubble1 in iter(bubbles): )
Also, you don't need to set bubble_old = bubble1. When you remove old_bubble from the list, you still hold the reference to it ( old_bubble is referenced to bubble1 ).
def touching(self, bubble, bubbles): for bubble1 in bubbles[:]: if self.color == bubble_old.color and dist(bubble.pos, bubble1.pos) <= 2 * BUBBLE_RADIUS: bubbles.remove(bubble1) self.touching(bubble1, bubbles)