Search code examples
pythonlist-comprehensionmultiplicationreplicate

Creating a list of mutable items repeated N times


I have a list containing a set of x mutable items. I would like to create another list where the set of x mutable items is repeated n times. However, the items must be references to unique objects rather than simply references to the original objects.

For example, let a = [[1],[2],[3]]. Suppose I would like the numbers inside to be repeated n=3 times, i.e. [[0],[2],[3],[1],[2],[3],[1],[2],[3]].

I can do this easily by using a * 3. The problem is that if I change a[0][0] = 0, then I will get a == [[0],[2],[3],[0],[2],[3],[0],[2],[3]], which is not desirable because I would like to change only the first element. Is there any other way to achieve this?


Solution

  • I just figured out I can do this through:

    from copy import deepcopy
    a = [[1],[2],[3]]
    n = 3
    b = [deepcopy(val) for _ in range(n) for val in a]
    

    Now if I set b[0][0] = 0, I will get b == [[0],[2],[3],[1],[2],[3],[1],[2],[3]].