1

Why does the following code

A = [[[0] * 3] * 3] * 3
A[2][2][2] = 1

print A

print this

[[[0, 0, 1], [0, 0, 1], [0, 0, 1]], [[0, 0, 1], [0, 0, 1], [0, 0, 1]], [[0, 0, 1], [0, 0, 1], [0, 0, 1]]]

instead of just setting one of the elements to 1?

Jessica
  • 2,335
  • 2
  • 23
  • 36
  • 2
    This is a duplicate of many questions; I chose one at random. See the [FAQ](http://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list). – DSM Nov 25 '13 at 00:25

1 Answers1

3

This is a fairly common question;

[0] * 3

results in a list containing three 0s, but

[[]] * 3

results in a list containing three references to a single actual list.

You need to do something like

A = [[[0] * 3] for j in range(3)] for k in range(3)]

to actually create what you want.

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99