-1

I've ran into an unexpected behavior when using a nested list in python, that took a while to debug. If a list is initialized like this:

a = [[None] * 2] * 2
a
[[None, None], [None, None]]

and another list initialized like this:

b = [[None, None], [None, None]]
b
[[None, None], [None, None]]

I would expect the same behavior from both these lists, but if I do:

a[0][0] = 3
a
[[3, None], [3, None]]

and if I do:

b[0][0] = 3
b
[[3, None], [None, None]]

Can someone explain the reason why this happens? thanks

fugas
  • 3
  • 2
  • its not as good as a debugger but sometimes putting your code into something like http://www.pythontutor.com/ can help you understand whats going on ... – Joran Beasley Feb 16 '16 at 00:39

1 Answers1

1
>>> a = [[None] * 2] * 2
>>> id(a[0])
41554168
>>> id(a[1])
41554168
>>> b = [[None, None], [None, None]]
>>> id(b[0])
41549576
>>> id(b[1])
41557368

This should explain

AlokThakur
  • 3,599
  • 1
  • 19
  • 32