Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove column from new matrix in Python without changing original matrix

Tags:

python

matrix

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!

like image 343
Mike S. Avatar asked Jan 29 '26 08:01

Mike S.


2 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]]
like image 137
PApostol Avatar answered Jan 31 '26 23:01

PApostol


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)

like image 26
Shadi Naif Avatar answered Jan 31 '26 23:01

Shadi Naif