Changing an element in one list changes multiple lists [duplicate]

I have a list of List say mysolution:

>>>mySolution
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> mySolution[0][0] = 1    
>>> mySolution
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

Intended output:

[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

why is it that all the 1st elements in my list of list's is being changed to 1? I would only like to change the first element of the first list to 1.


What matters is how you created your original mysolution list. As it seems, it contains four times the same list which is why changing it once will make it change in all four locations.

To initialize independent zero-filled lists like that, you can do the following:

mysolution = [[0] * 4 for i in range(4)]

It's quite possible that you created the list like this:

mySolution = [0]*4
mySolution = [mySolution]*4

Or equivalently:

mySolution = [[0]*4]*4

Either of the above snippets will create a list with four sublists which are copies of the exact, same sublist, so any modification on one sublist will be reflected on the others - they're one and the same. The solution is to create four different sublists:

mySolution = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Or a bit shorter:

mySolution = [[0]*4 for _ in xrange(4)]