1

Consider the following two pieces of code in Python interpreter 3.6-

>>> d = {0:[[1,2],[3,4]]}
>>> d[1] = [[0]*2]*2
>>> d
{0: [[1, 2], [3, 4]], 1: [[0, 0], [0, 0]]}
>>> d[1][0][0] = 5
>>> d
{0: [[1, 2], [3, 4]], 1: [[5, 0], [5, 0]]}

and

 >>> d = {0:[[1,2],[3,4]] , 1 : [[0,0],[0,0]]}
 >>> d
 {0: [[1, 2], [3, 4]], 1: [[0, 0], [0, 0]]}
 >>> d[1][0][0] = 5
 >>> d
 {0: [[1, 2], [3, 4]], 1: [[5, 0], [0, 0]]}

Why are they giving different values of d[1] when the only difference is the way the list of zeroes is created?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
zahlen
  • 73
  • 2
  • 11

1 Answers1

0
>>> d = {0:[[1,2],[3,4]]}
>>> d[1] = [[0]*2]*2 #You are using the same address of the list to create the second list
>>> d
{0: [[1, 2], [3, 4]], 1: [[0, 0], [0, 0]]}
>>> d[1][0][0] = 5
>>> d
{0: [[1, 2], [3, 4]], 1: [[5, 0], [5, 0]]}

So if you change the value of one memory address the other one changes.

>>> d = {0:[[1,2],[3,4]]}
>>> d[1] = [[0]*2,[0]*2] #Now we are creating two list of different address
>>> d
{0: [[1, 2], [3, 4]], 1: [[0, 0], [0, 0]]}
>>> d[1][0][0] = 5
>>> d
{0: [[1, 2], [3, 4]], 1: [[5, 0], [0, 0]]}

In the above code you could feel the difference. The answer for your question is the Memory address is the reason.

Edit:

It is applicable to any value not only zeroes

Yashik
  • 391
  • 5
  • 17