0

When I build a list in a class, the objects build from that class share the same list. I mean, changes in the list of obj1 will happen in obj2's list.

That doesn't happen with other data types like strings.

Why that happens?

And how can I avoid that?

There goes an example:

class Class:
    list = list()
    def list_appender(self,arg):
        self.list.append(arg)

obj1 = Class()
obj2 = Class()

obj1.list_appender(4)
obj1.list_appender(5)
obj1.list_appender(6)
print(obj2.list)

Answer = [4, 5, 6]

Rommel
  • 69
  • 1
  • 5
  • Lists are mutable. All classes contain a pointer to the same list – mousetail Mar 24 '21 at 12:11
  • You can view the memory location of each list and see that they have the some spot using `id(my_list)`. If you want to create a list that is the same but has a different memory location, use `new_list = old_list[:]`. – Jeff Gruenbaum Mar 24 '21 at 12:13

0 Answers0