Remove column from new matrix in Python without changing original matrix

Viewed 116

I'm new to programming and I'm stuck with this problem in Python. Take note that I can't use numPy in this code. So I copied matrix to new_matrix. I want to delete the first row and column in new_matrix without changing anything in the original matrix. Here is the code:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_matrix = matrix.copy()
print('old: ', matrix)
print('new: ', new_matrix)

for i in range(len(new_matrix)):
    del new_matrix[i][0]
print('old: ', matrix)
print('new: ', new_matrix)

del new_matrix[0]
print('old: ', matrix)
print('new: ', new_matrix)

The result is this:

old:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
old:  [[2, 3], [5, 6], [8, 9]]
new:  [[2, 3], [5, 6], [8, 9]]
old:  [[2, 3], [5, 6], [8, 9]]
new:  [[5, 6], [8, 9]]

Why does it keep deleting the first column of the original matrix? Help!

3 Answers

I would recommend to read about the difference between shallow and deep copy.

import copy

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_matrix = copy.deepcopy(matrix)

print('old: ', matrix)
print('new: ', new_matrix)

for i in range(len(new_matrix)):
    del new_matrix[i][0]
    
print('old: ', matrix)
print('new: ', new_matrix)

del new_matrix[0]
print('old: ', matrix)
print('new: ', new_matrix)

Output:

old:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
old:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new:  [[2, 3], [5, 6], [8, 9]]
old:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new:  [[5, 6], [8, 9]]

replace:

new_matrix = matrix.copy()

with:

new_matrix = copy.deepcopy(matrix)

because the first one is copying only the first level which is a (list of list-references)

you have to import copy libraray which is inbuilt in python then do deepcopy()

import copy
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_matrix = copy.deepcopy(matrix)

print('old: ', matrix)
print('new: ', new_matrix)

for i in range(len(new_matrix)):
    del new_matrix[i][0]
print('old: ', matrix)
print('new: ', new_matrix)

del new_matrix[0]
print('old: ', matrix)
print('new: ', new_matrix)

Output

old:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
old:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new:  [[2, 3], [5, 6], [8, 9]]
old:  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new:  [[5, 6], [8, 9]]
Related