-2

I am taking a quick course Python programming and I learn a quick way to initialize an array in Python by using the * operator. I am trying to extend it to a 2d case.

A = [[0]*3]*3

I then try to modify the [0][1] element to specific value but I found that all elements on the middle column are changed at the same time. For example,

A[0][1] = 888

It results in A[0][1] = 888, A[1][1] = 888, A[2][1] = 888. I really don't see how this happens. It seems like that all elements are linked and refer to the same address. But if I change the initialization code to

A = [[0,0,0],[0,0,0],[0,0,0]]

The problem is gone. I just wonder what is wrong with the first approach. Any fast way to initialize the array with certain value but without explicitly specify the elements?

petezurich
  • 7,683
  • 8
  • 34
  • 51
user1285419
  • 2,113
  • 7
  • 45
  • 68

1 Answers1

0

You could try this:

a = [[0 for i in range(3)] for o in range(3)]
Unicone
  • 188
  • 1
  • 8