1

The following code surprised me.

alist = [[]] * 4

alist[0].append(100)

I expected that alist would be

[[100],[],[],[]]

but it turned out to be

[[100],[100],[100],[100]]

Does anyone know why python works that way? thank you.

kederrac
  • 16,819
  • 6
  • 32
  • 55
吳健平
  • 19
  • 2
  • That's the difference of value and reference.list is same as reference. – stars seven Mar 02 '20 at 18:52
  • You could check that is the same reference with help of `is` such that `alist[0] is alist[1]` is True but in other case `alist = [[] for _ in range(4)]` all references will be points to a 4 different empty list objects. Also check that `alist[0] is []` is False. – frost-nzcr4 Mar 02 '20 at 21:05

2 Answers2

1

on this line alist = [[]] * 4 you are creating one inner list and 4 references to the same list, to fix this you can use:

alist = [[] for _ in range(4)]
kederrac
  • 16,819
  • 6
  • 32
  • 55
0
alist1 = [[] for _ in range(4)]
alist1[0] = 100
print(alist1)
vijju
  • 21
  • 2