I've got a project where there is a list that contains a large number of user-defined objects. Each object itself has a variable that contains a list of its own. Why is it that when I append something to the list inside of each object, it gets applied to every object in the master list?
Take the following code for example:
class Example:
inner_arr = []
def __init__(self,name):
self.name = name
class_list = []
for i in range(10):
class_list.append(Example("Trial #:{i}".format(i=i)))
for i in range(len(class_list)):
if i % 3 == 0:
class_list[i].inner_arr.append("Divisible by 3")
for i in class_list:
print(i.inner_arr)
In theory, the ".append('Divisible by 3')" should only be applied to the 1st, 4th, 7th, and 9th objects in the class_list, so the expected result should look like this:
['Divisible by 3']
[]
[]
['Divisible by 3']
[]
[]
['Divisible by 3']
[]
[]
['Divisible by 3']
But instead we get this mess:
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
['Divisible by 3', 'Divisible by 3', 'Divisible by 3', 'Divisible by 3']
I've tried rewriting this using dictionaries, using every possible method for updating lists. Strangely enough this behavior only occurs when the object's variable is a list. If the object's variable is a string, it works exactly as expected. I'm sure this is user error, but I cannot figure out what I am missing in all of this. Any help or advice is appreciated. Thanks in advance.