0

It might be a very stupid question but I just don't understand this code:

>>> a=[[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][1]=3
>>> a
[[0, 3, 0], [0, 3, 0], [0, 3, 0]]

Why a call a[0][1] will initialize the whole second column to be 3?

Shawn
  • 1,598
  • 1
  • 12
  • 19

1 Answers1

0

This is because a[0][1] actually is the reference to the same lists. When you use * operator to duplicate elements into a list, these duplicate elements are not individually stored in the memory. They point to the same list, so if you modify one list, all the lists would be modified.

Saksham Varma
  • 2,122
  • 13
  • 15
  • I see. I got misled by some answers on stack overflow saying this would initialize a 2-D array. which doesn't. – Shawn May 01 '15 at 23:29