A = [[], []]
B = [[]] * 2
for i in range(2):
    A[i].append(500 + i)
    B[i].append(800 + i)
 
print("A =", A)
print("B =", B)

Output:

A = [[500], [501]]
B = [[800, 801], [800, 801]]

Why B behaves differently than A

This is another classic reference bug in Python:

  • A = [[], []] creates two independent empty lists in memory.
    • A[0] and A[1] point to different list objects.
    • A[0].append(500) updates only the first list.
    • A[1].append(501) updates only the second list.
  • B = [[]] * 2 creates a list with two references pointing to the EXACT same inner list in memory.
    • B[0] and B[1] are aliases for the same object.
    • When i = 0, B[0].append(800) modifies the shared list [800].
    • When i = 1, B[1].append(801) modifies the same shared list [800, 801].
    • Since both elements of B point to this single list, printing B shows [[800, 801], [800, 801]].