Newb18
Newb18

Reputation: 167

Python copy matrix

So i have a quick question my code is supposed to delete the row and column (from i and j) which it does but for some reason it also changes the original matrix (while i have copied it). Can someone tell me why that is?

def reduce_matrix(M, i, j):
    newM=list(M[:])
    for q in range(len(newM)+1):
        if q==i-1:
            del newM[q]
    for y in range(len(newM)):
        for x in range(len(newM[y])):
            if x==j-1:
                del newM[y][x]
    return newM

Upvotes: 0

Views: 1161

Answers (2)

itzMEonTV
itzMEonTV

Reputation: 20349

You have to copy all sublists in a list, instead of copy all list.

try this:

def reduce_matrix(M, i, j):
    newM=[k[:] for k in M]
    #rest of code

From your program:. Try to print id of each sublists.

def reduce_matrix(M, i, j):
    newM=list(M[:])
    print id(M[0]), id(M[1]), id(M[2])
    for q in range(len(newM)+1):
        if q==i-1:
            del newM[q]
    for y in range(len(newM)):
        for x in range(len(newM[y])):
            if x==j-1:
                del newM[y][x]
    return newM

lis = [[1,2,3],[3,4,5],[7,4,2]]
print id(lis[0]), id(lis[1]), id(lis[2])
reduce_matrix(lis, 1, 1)

>>>
3074546604 3072046316 3072047084
3074546604 3072046316 3072047084

That proves that, sublists are just tagging or pointing to another variable.So modification for any sublist will happen to every sublist with same tags.

For example:

a = [1,2]
b = a
c = a
b.append(3)
print a
print b
print c
>>>
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]

Hope this helps.

Upvotes: 1

SolaWing
SolaWing

Reputation: 1722

you only copy the first list, not the sublist. if you want to return a new matrix with reduce row and column, you can do this:

def reduce_matrix(M, i, j):
    return [[M[m][n] for n in range(len(M[m])) if j-1 != n ] \
               for m in range(len(M)) if i-1 != m]

Upvotes: 1

Related Questions