0

I define a two-dimension array in python like this:

a = [[1]*3]*3

and I want to assign one element to be 2, like:

a[1][1] = 2

However, a turns out to be:

[[1,2,1],[1,2,1],[1,2,1]]

Instead of what I thought like this:

[[1,1,1],[1,2,1],[1,1,1]]

Anyone has any idea?

The ScreenShot of the code

2 Answers2

0

You can do it using list comprehension:

a=[[1 for _ in range(3)] for _ in range(3)]

a
Out[32]: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]

a[1][1]=2

a
Out[34]: [[1, 1, 1], [1, 2, 1], [1, 1, 1]]
Erlinska
  • 433
  • 5
  • 16
0

I think that having brackets inside brackets is making a None value item at 0 and that it is multiplying/unpacking the inside multiplication first, so that your reference a[1][1] is referring to the meta list [[1,1 1]*3]and coming up with the second element of the the second element of that switching it to 2 before the second multiplication takes place, because of order of operations.