Search code examples
pythonlistequalitymultiplication

Simple python question: two equal lists acting differently


I create a list in python using multiplication and a second more explicitly. I check that they are equal and then attempt to alter the same element in each. This alteration acts differently for each one. The code:

list1 = [[0]*2]*2
list2 = [[0, 0], [0, 0]]
print(list1 == list2)

list1[0][0] = 3
list2[0][0] = 3
print(list1)
print(list2)

prints out:

True
[[3, 0], [3, 0]]
[[3, 0], [0, 0]]

What is going on? Why is a multiply-initiated list acting differently?


Solution

  • I believe this happens because in multiplying a list, you are simply making a reference to the existing object, so anything you do to the original, will be done to all of the references too.

    You want to do this instead:

    list1 = [[0] * 2 for x in range(2)]