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?
Solution: use list comprehension
class SomeClass:
def __init__(self):
self.foo = None
some_list = [SomeClass() for _ in range(5)]