Mike S.
Mike S.

Reputation: 33

Remove column from new matrix in Python without changing original 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!

Upvotes: 3

Views: 189

Answers (3)

PApostol
PApostol

Reputation: 2292

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]]

Upvotes: 3

Adhun Thalekkara
Adhun Thalekkara

Reputation: 723

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]]

Upvotes: 2

Shadi Naif
Shadi Naif

Reputation: 184

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)

Upvotes: 2

Related Questions