Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy of nested list gets bigger when appending to original

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading