79764427

Date: 2025-09-14 16:41:00
Score: 1
Natty:
Report link

As you started to uncover according to your comment, lists are not copied when operated on, and in particular when declaring [] as a class attribute it gives you an empty list with some address on your CPU, that is shared between all classes (which is not the case with types that create copies of your variables).

See these links 1, 2, that globally show you this:

class Dog:

    tricks = []             # mistaken use of a class variable

    def __init__(self, name):
        self.name = name

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']
class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']

Forgetting about this behaviour for lists and dicts (which does not exist for tuples, int, strings, floats) is maybe the most common error in Python.

Reasons:
  • Blacklisted phrase (1): these links
  • RegEx Blacklisted phrase (1): See these links
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: globglogabgalab