-1

Say I have the following class:

class Elem():
    def __init__(self, valAcum=0, data=0, prev=0):
        self.valAcum = valAcum
        self.data = data
        self.prev = prev

And then, I do the following:

D = [Elem()] * 3
D[0].data = 3
print(D) 
# [(0, 3, 0), (0, 3, 0), (0, 3, 0)]

What is happening? Doing D[i].f = x sets f = x in every element from D. Why is this happening? How can I avoid it?

Mureinik
  • 297,002
  • 52
  • 306
  • 350

1 Answers1

0

Your list has three references to the same Elem object. When you modify it, the change will be visible through all those reference since they all refer to the same object.

Instead, you should create three different objects. E.g.:

D = [Elem() for _ in range(3)]
Mureinik
  • 297,002
  • 52
  • 306
  • 350