Home > Software design >  Copy of nested list gets bigger when appending to original
Copy of nested list gets bigger when appending to original

Time:12-16

I encountered a problem in this code snippet:

temp = matrixInput.copy()
for iy in range(len(temp)):
    for runde in range(1, 5):
        for ix in temp[iy]:
            print("iy:", iy, "ix:", ix, "runde", runde, "len:", len(temp[iy]))
            newnumber = ix   runde
            if newnumber > 9:
                newnumber -= 9
            matrixInput[iy].append(newnumber)

matrixInput is a list of lists (matrix if you want) with a whole bunch of integers.

The idea is to create a copy, iterate over the copy and append to the original. Do this 4 times and every time the value in the appended number should increase by 1. The goal is to get a matrix 5 times as big as initial.

So far so good. But for some reason when I append to matrixInput the most inner loop gets stuck and endlessly appends. temp[iy] actually gets bigger and bigger despite me appending to matrixInput[iy]. What is my mistake?

CodePudding user response:

as mentioned in the comment list.copy() is shallow, a solution would be to use the deepcopy method from copy library

import copy
...
temp=copy.deepcopy(matrixInput)
  • Related