0

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"?

Doug D.
  • 3
  • 1

1 Answers1

0

Use a list comprehension:

tests = [Test(1) for _ in range(100)]

The above creates 100 different Test objects.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • That worked, excellent! It also seemed to populate the list very fast. Thanks very much. – Doug D. Feb 20 '21 at 23:05
  • I just saw that the answers to question 240178, "list-of-lists-changes-reflected-across-sublists-unexpectedly", explain why list multiplication doesn't work. – Doug D. Feb 20 '21 at 23:16
  • @DougD. I'm adding a link for that: https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly so people don't have to copy and paste. – Grifball Feb 24 '21 at 21:16