Home > Mobile >  How do I add a variable that stores a class to a list multiple times?
How do I add a variable that stores a class to a list multiple times?

Time:12-09

Im working on this project and I noticed that if you have a class stored in a variable, and you append that variable to a list multiple times, then if you change the class on one index, you will change it on every index.

Python:

class myClass():
    def __init__(self,value):
        self.value = value

a = myClass(3)

l = []

for i in range(5):
    l.append(a)

l[0].value = 1

for i in l:
    print(i.value)

The output is:

1
1
1
1
1

How do I make the output look like this:

1
3
3
3
3

Any fixes?

CodePudding user response:

That is because unlike the basic types, the variable doesn't actually stores the data or the values of the object, it is storing a location or address in the memory that stores (points to) the location of the data of the object. This is pointer of the object.

As you append this variable to a list, all indexes in list will point to the same address in the memory. Thus, when you change one index, you change the value in the memory, which all of the indexes are pointing at and you could see the changes from all of the indexes.

To prevent this from happening you have to create a copy of that same object. The copy will have the same properties, but it won't be stored at the same location so it won't affect/be affected from the other objects.

You can do it like that:

class myClass():
    def __init__(self,value):
        self.value = value

l = []

for i in range(5):
    a = myClass(3)
    l.append(a)

l[0].value = 1

for i in l:
    print(i.value)

Output:

1
3
3
3
3
  • Related