pythonlistinstancecloneconstruction

Is there a Pythonic way to create a list of cloned items?


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

  • Solution: use list comprehension

    class SomeClass:
        def __init__(self):
            self.foo = None
    
    some_list = [SomeClass() for _ in range(5)]