0

This is my line of code:

>>> table = [[0] * 3] * 3
>>> table
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> table[1][1] = 99

and it yields the below result:

>>> table
[[0, 99, 0], [0, 99, 0], [0, 99, 0]]

Then, there is this below line of code:

>>> tab = [[0 for i in range(3)] for j in range(3)]
>>> tab
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> tab[1][1] = 99

But this yields a different result:

>>> tab
[[0, 0, 0], [0, 99, 0], [0, 0, 0]]

Both are the same lists. Same assignment. But how come they yield different results? Someone please help me understand.

Vignesh
  • 11
  • 1
  • 2
  • 8
    Possible duplicate of [Python - Using the Multiply Operator to Create Copies of Objects in Lists](https://stackoverflow.com/questions/1605024/python-using-the-multiply-operator-to-create-copies-of-objects-in-lists) – mkrieger1 Jul 16 '19 at 07:27
  • 2
    Oops, better https://stackoverflow.com/q/240178/4621513 – mkrieger1 Jul 16 '19 at 07:29
  • In the first case the `[0]` is evaluated **once** and then multiplied twice. In the second case the `0` is evaluated **for every** item combination of the ranges. So it is one list with many references vs. multiple lists. – Klaus D. Jul 16 '19 at 07:30
  • When you are using multiplication operator * it makes new references to the existing sublist instead of trying to make new sublists. When you then modify this single item of sublist it is visible via all three references to it. – ncica Jul 16 '19 at 07:38
  • 1
    Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Georgy Jul 16 '19 at 08:17

0 Answers0