Unexpected issue with List initialization

46 views Asked by At

I found something a bit weird when playing with lists. I usually use print() to debug or understand how things work but in this case the print() outputs are not helping me at all.

Here is a simple code, you will 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 was expecting a to behave like b, but it doesn't. Can someone explain this?

0

There are 0 answers