-1

I notice this interesting thing in python:

>>> B = [[]*5 for _ in range(5)]
>>> B
[[], [], [], [], []]
>>> B[0].append(1)
>>> B
[[1], [], [], [], []]
>>>

Then I do this:

>>> B = [[]]*5
>>> B
[[], [], [], [], []]
>>> B[0].append(1)
>>> B
[[1], [1], [1], [1], [1]]
>>>

It seems B = [[]]*5 and B = [[]*5 for _ in range(5)] generate the same empty list B but why they behave different when using append? Thank you for anyone who cares to explain!

Ping Yuan
  • 1
  • 1

1 Answers1

0

Because in second one you don't create new empty list. you just add the same list 5 time. Because of that when you select the first one and append to it t will affect on all of them. Because all are the same.

try this for sure in second one:

print(B[0] is B[1])
heydar dasoomi
  • 527
  • 1
  • 4
  • 19