Strange behavior of lists in python [duplicate]

When you multiply a list, it copies a reference to the list, it doesn’t create a copy of the list. As lists are mutable, when you change it, it is changed for all the references to it.

In ASCII-art terms:

a1 --- [list1, list2] --- list1 = [0, 0]
                      --- list2 = [0, 0]

a2 --- [list3, list3] --- list3 = [0, 0]

You can clearly see that changing list3 will affect both positions.

If you want to create variable-length lists without copying references, you should instead do something like this:

>>> a2 = [[0]*2 for _ in range(2)]
>>> a2[0][0] = 1
>>> a2
[[1, 0], [0, 0]]

Here we are using a list comprehension in order to create new elements each time, rather than copying references to old elements. In more complex situations, where you have existing mutable objects you want to repeat, you might want to use the copy module.

Note the [0]*2 operation is still OK, as ints in Python are immutable, and can’t change, so it doesn’t matter if you have references to the same object.

Leave a Comment