0

I create a list using the below codes.

a = [[False] * 3] * 3

which creates a 3x3 matrix with all elements of False value.

And when I changed a[0][0] to be True using a[0][0] = True, the result is:

[[True, False, False], [True, False, False], [True, False, False]]

where the entire first column changes into True.

However, if I create a using the for loop, like:

a = [[False] * 3 for i in range(3)]

or

a = [[False for i in range(3)] for i in range(3)]

And after executing the same a[0][0] = True, I get my desired result in both ways as:

[[True, False, False], [False, False, False], [False, False, False]]

where just one element is changed into True.

Why there is such difference in creating the list in Python? Thank you for answering!

1 Answers1

1
  • [False] * 3 gives us a list of 3 references of the same False, but since boolean is immutable, each one of those is independent.
  • [[False] * 3] * 3 gives us a list of 3 references of the same [False] * 3, and since list is mutable, those 3 lists are actually the same.
  • a = [[False] * 3 for i in range(3)] is equivalent to:
a = []
for i in range(3):
    a.append([False] * 3)

That should tells you why the lists are different.

  • For [[False for i in range(3)] for i in range(3)], the only difference from above is that the Falses are created independently, but since boolean is immutable anyway, the result is identical to the above.
kwkt
  • 1,058
  • 3
  • 10
  • 19
  • "3 copies of" is inaccurate. It's the same object 3 times - or in other words, 3 references to the same object. This is true regardless of whether the object is mutable. – user2357112 Jan 15 '21 at 01:42
  • @user2357112supportsMonica That's true, let me edit my answer. – kwkt Jan 15 '21 at 01:43