1

I am trying to understand why the following behaviour exists in Python.

If I make two equivalent matrices

matrix1 = [[False] * 3] * 3
matrix2 = [[False for x in range(3)] for y in range(3)]

Then I try to make the top left cell equal to True.

matrix1[0][0] = True
matrix2[0][0] = True

Each array was changed in a different way.

matrix1 is now [[True, False, False], [True, False, False], [True, False, False]]
matrix2 is now [[True, False, False], [False, False, False], [False, False, False]]

matrix2 is the behaviour I was expecting. Why does matrix1 behave differently?

martineau
  • 119,623
  • 25
  • 170
  • 301
Osloyeah
  • 21
  • 3
  • 3
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/a/2612815/8881141) – Mr. T Jan 07 '22 at 18:19

1 Answers1

2

When you use []*3, each element points to the same object, so changing one changes the others. You can think of it as a way to multiply the elements in a list.

When you use [for x in range(3)], it creates three separate items. Changing one item doesn't affect the others.

Cameron
  • 389
  • 1
  • 9
  • See https://stackoverflow.com/questions/6007881/what-does-the-0x-syntax-do-in-python/6007901 for more info. – Cameron Jan 07 '22 at 18:24