-1

I have trouble declaring a two-dimensional list in Python. Below are two different matrices; A and R. When changing the content of a single cell I am successful in the R-matrix, but not so much in the A-matrix, as the value-input affect the entire column and not only the single cell. Why does this happen? I would prefer the A-style of declaring the matrix.

n=6

A = [[0]*n]*n    
R=[[0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0]]

R[1][1]=5
A[1][1]=5

print(R)
print(A)

The output from the two operations is:

[[0, 0, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
[[0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0]]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
Enthuziast
  • 1,195
  • 1
  • 10
  • 18

1 Answers1

1

A = [[0]*n]*n creates multiple copies of the same list. This is why changing one affects every other one

Mayowa Ayodele
  • 549
  • 2
  • 11