I found an interesting and confusing phenomenon when I was coding, and I did some test. Here is the test code.
testlist = [[]]*2
for i in range(2):
for j in range(11):
if j%2==i:
testlist[i].append(j)
print(testlist)
I thought the output should be
[[0, 2, 4, 6, 8, 10], [ 1, 3, 5, 7, 9]]
but the output actually is
[[0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9], [0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9]]
And I changed my code a little bit
testlist = [[]]*2
for i in range(2):
for j in range(11):
if j%2==i:
testlist[0].append(j)
print(testlist)
note that only testlist[0] is mentioned so testlist[1] shouldn't be changed at all, but the output is still
[[0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9], [0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9]]
This confuses me so much and a possible explanation I come up with is that by using [[]]*2, testlist[0] and testlist[1] are pointing to the same object. Because the following code runs well.
testlist = [[],[]]
for i in range(2):
for j in range(11):
if j%2==i:
testlist[i].append(j)
print(testlist)
[[0, 2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
Can anybody give me a solid explanation? And If I want to make a list of 1000 empty lists, how can I do that without typing 1000 []s?