I'm new to Python, and need to create a list with multiple instances of a data class. I tried using list multiplication to do this, because I figured it would be faster since I'd have to 'append' thousands of individual instances of my data class. However, my list multiplication seems to create objects that all reference the same instance of my data class, rather than to multiple independent instances of my data class.
Here's the simple example that I tried:
class Test: # define data class "Test".
def __init__(self, a):
self.a = a
test = Test(1) # define an instance of data class "Test".
tests = [test] * 2 # define a list called "tests", with 2 instances of "test".
print(tests[0].a) # both instances of 'a' in the list show that "a = 1".
print(tests[1].a)
tests[0].a = 2 # change the first instance of 'a' in the list to "a = 2".
print(tests[0].a) # first instance of 'a' properly changed to "a = 2".
print(tests[1].a) # but, the second instance of 'tests.a' ALSO changed from 1 to 2!
I had expected that changing one instance in the list wouldn't affect the other instance, but it looks like what I actually have is multiple copes of the same instance. So, how can I create a list with multiple, independent instances of my data class "Test"?