Unexpected problem initializing the list

I found something strange while playing with list

s. I usually use it print()

for debugging or understanding how things work, but in that case the outputs print()

don't help me at all.

Here's a simple code, you can quickly see what I'm talking about:

a = [[]] * 5

b = [[]] * 5
b[0] = []
b[1] = []
b[2] = []
b[3] = []
b[4] = []

# It prints the same thing:
print(a)  # [[], [], [], [], []]
print(b)  # [[], [], [], [], []]

a[0] += ["test"]
b[0] += ["test"]

# Different results:
print(a)  # [['test'], ['test'], ['test'], ['test'], ['test']]
print(b)  # [['test'], [], [], [], []]

      

I expected it a

to behave like b

, but it doesn't. Can someone explain this?

+3


source to share





All Articles