The code below creates a list of objects that contains a list as attribute and a method to append items to this list but this appending is not working like I expected.
What I expected:
Each list MyList
inside of each object MyObj
to have only 3 elements.
How it is working:
The list MyList
inside of MyObj[0]
has 3 elements
The list MyList
inside of MyObj[1]
has 6 elements
The list MyList
inside of MyObj[2]
has 9 elements
It seems to me the object MyObj[i]
appends the MyList
of prevous object MyObj[i-1]
. How the code should be like to make each list MyList
of each MyObj[i]
have only the 3 elements inserted by the method add_to_list
?
Python code:
class MyClass:
MyList = []
def add_to_list(self):
for item in range(3):
self.MyList.append("Item " + str(item))
MyObj = []
for i in range(3):
MyObj.append(MyClass())
MyObj[i].add_to_list()
print("Object " + str(i))
print(MyObj[i].MyList)