1

When I execute the code below

    A = [[None] * 3] * 3
    print(A)
    A[0][0] = 1
    print(A)

The two prints return

    [[None, None, None], [None, None, None], [None, None, None]]
    [[1, None, None], [1, None, None], [1, None, None]]

The statement A[0][0] = 1 assigns the value 1 to A[0][0], A[1][0], and A[2][0] instead of just assigning it to A[0][0]. Why is this the case?

hokkaidi
  • 858
  • 6
  • 19
  • 1
    You have the same reference inside `A` - check them with `print(id(A[0]))` and `print(id(A[1]))`. Use `A = [[None for _ in range(3)] for _ in range(3)]` - never use the `A = [[None] * 3] * 3` syntax to create nested lists – Patrick Artner Apr 18 '20 at 15:06

0 Answers0