0

can someone please explain why this is happening, the problem is when I update the value of the matrix its duplicate matrix (a) also get updated automatically so Is there any way to keep the value of duplicate matrix as what it is?

python3

matrix=[[1,2,3],[4,5,6],[7,8,9]]
a=matrix
for i in range(len(a)):
    for j in range(len(a)):
        matrix[i][j]=a[j][len(a)-1-i]
        print(a)

Output

[[3, 2, 3], [4, 5, 6], [7, 8, 9]]
[[3, 6, 3], [4, 5, 6], [7, 8, 9]]
[[3, 6, 9], [4, 5, 6], [7, 8, 9]]
[[3, 6, 9], [6, 5, 6], [7, 8, 9]]
[[3, 6, 9], [6, 5, 6], [7, 8, 9]]
[[3, 6, 9], [6, 5, 8], [7, 8, 9]]
[[3, 6, 9], [6, 5, 8], [3, 8, 9]]
[[3, 6, 9], [6, 5, 8], [3, 6, 9]]
[[3, 6, 9], [6, 5, 8], [3, 6, 3]]

1 Answers1

0

This happens because the new list is referencing or pointing to the same old list object.

if you need the original list unchanged when the new list is modified, you can use the copy() method.

my_list = ['cat', 0, 6.7]

new_list = my_list.copy()
new_list.append('c')

print('old List:', my_list)
print('Copied List:', new_list)

or you can also use list slicing

my_list = ['cat', 0, 6.7]

new_list = my_list[:]
new_list.append('c')

print('old List:', my_list)
print('Copied List:', new_list)

Output of both will be same

old List: ['cat', 0, 6.7]
Copied List: ['cat', 0, 6.7, 'c']
gala
  • 66
  • 2
  • 5