-1

Consider the following code:

class SomeClass:
    def __init__(self):
        self.foo = None

some_list = [SomeClass()] * 5

The problem with this code is that all 5 items of some_list refer to the same instance of SomeClass. If I do some_list[0].foo = 7, then I get some_list[1].foo equal to 7, etc.

So how to instantiate N different SomeClass instances in a list?

Serge Rogatch
  • 13,865
  • 7
  • 86
  • 158

1 Answers1

3

Solution: use list comprehension

class SomeClass:
    def __init__(self):
        self.foo = None

some_list = [SomeClass() for _ in range(5)]
Jordan Singer
  • 567
  • 5
  • 11