Gregory Varner
Gregory Varner

Reputation: 11

Defining a new list so that modifications do not affect the original without importing copy

I know that there have been several similar discussions on this topic and I have tried to implement at least one (a list comprehension). The main issue is that my original list (it is actually a matrix set up as a list of lists) is being modified by part of my code, but I can not seem to figure out why.

Here is the code that I have

def eliminate_row_column(mat,k,l):
    new_matrix = [i for i in mat]      #creates a new temp matrix
    new_matrix.pop(k)        #eliminates the kth row
    for i in range(len(new_matrix)):
        new_matrix[i].pop(l)     #eliminates the lth column
    return new_matrix

It appears to be removing the kth element (the kth row) without modifying the original. However, when I enter the for loop it appears to be modifying the original input list.

It appears that using a deep copy might resolve the issue, but I will need this code to work in context where (students) can not import in.

I am not a programmer by training and this one is giving me a bit of a headache. Any help would be appreciated.

Upvotes: 0

Views: 58

Answers (2)

Gregory Varner
Gregory Varner

Reputation: 11

Thanks to Barmar for the correct solution. I am including the corrected code below to show the fix. Obviously you can use numpy instead, but this works without it.

def eliminate_row_column(mat,k,l):
    new_matrix = [[t for t in row ] for row in mat]    #creates a new temp matrix
    new_matrix.pop(k)        #eliminates the kth row
    for i in range(len(new_matrix)):
        new_matrix[i].pop(l)     #eliminates the lth column
    return new_matrix

Upvotes: 0

wjandrea
wjandrea

Reputation: 32944

In this line, i references the existing lists, which are not copied.

new_matrix = [i for i in mat]

You can simply copy them:

new_matrix = [i.copy() for i in mat]

By the way, for what it's worth, a list of lists is not really a matrix. You could use a NumPy array if you wanted a proper matrix.

Upvotes: 1

Related Questions