Possible Duplicate:
Unexpected feature in a Python list of lists
I want to make a list of lists in Python, but apparently this doesn’t work, as changing one number changes several. Why is this, and how can I fix it?
>>> a = [[0]*3]*4
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
What you’ve discovered is a classic Python pitfall.
x = [0]*3is a list. No problem there, but[x]*4creates a list with 4 references to the exact same listx. So modifying the first element,x, also modifies the other elements as well.Instead, if you do this:
then you get 4 distinct items in the list: