Something is mutating my list and I dont know what

Question:

I have a matrix that I want to mutate using the propigate() function. It takes the mappp matrix and pretty much makes a mutation of it if certain conditions are me within each row. This is a function that I built to find relationships amount the elements of the matrix. That’s not important to the issue. So when I pass in my starting matrix, I expect propigate() to spit out a mutated function, but leave the starting function unchanged. I thought I took care of mutations with copy() after I checked for places where I may have mutated the starting matrix on accident. I cant see where my mistake is, but I feel that I may have something to do with how I am using enumerate here.

mappp is a matrix that relates rows to each other by the value in each rows column 0 means the associated,
1 means that the row is close by, -1 means that the rows have no idea about each other. After running propigate() each zero expands to its neighbor ( those entries with 1) then I multiply that row by -1 and its close neighbors. It’s a lot to explain, hopefully I’m missing something simple here.

THE STARTING MATRIX THAT I DON’T WANT TO MUTATE

mappp = [[0,-1,1,1,-1],
       [-1,0,1,-1,1],
       [1,1,0,-1,-1],
       [1,-1,-1,0,-1],
       [-1,1,-1,-1,0]
       ]

PROPIGATE THAT CHANGES MY mappp

def propigate(matrix):
    mapp1degree = matrix.copy()
    for idy, row in enumerate(mapp1degree):
        holder = []
        for idx, element in enumerate(row):
            if element == 1:
                mapp1degree[idy][idx] = 0
                holder.append(idx)
        print(holder)
        for i in holder:
            mapp1degree[idy] = add_twoList([-1 * x for x in mapp1degree[-1]], mappp[i])
    return mapp1degree

BOILER PLATE TO ADD TWO LISTS

def add_twoList(L1, L2):
    res_lt = []  # declaration of the list
    for x in range(0, len(L1)):
        res_lt.append(L1[x] * L2[x])

EXPECTED OUT PUT SHOULD BE

propigate(mappp)

[[0,1,0,0,-1],[1,0,0,-1,0],[0,0,0,1,1],[0,-1,1,0,-1],[-1,0,1,-1,0]]

I tried using copy() on the passed in matrix but that didn’t help, and I even tried using the variable from outside the function.

Asked By: oscar

||

Answers:

.copy() only produces a shallow copy. Since you have a list of lists, use copy.deepcopy so that the inner lists are copied as well. (This could also be achieved with a nested list comprehension.)

import copy
# ...
mapp1degree = copy.deepcopy(matrix)
Answered By: Unmitigated
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.