3

Possible Duplicate:
Python list problem

I don't understand behavior of lists in python:

>>> a1 = [[0,0],[0,0]]
>>> a2 = [[0]*2]*2
>>> a1
[[0, 0], [0, 0]]
>>> a2
[[0, 0], [0, 0]]
>>> a1[0][0] = 1
>>> a2[0][0] = 1
>>> a1
[[1, 0], [0, 0]]
>>> a2
[[1, 0], [1, 0]]

Why assignment of one element affects to another element? Thanks for answers!

Community
  • 1
  • 1
maxsocl
  • 484
  • 3
  • 9
  • Relevant Python FAQ about [multi-dimensional lists](http://docs.python.org/faq/programming.html#how-do-i-create-a-multidimensional-list) – Praveen Gollakota Apr 17 '12 at 13:00

1 Answers1

7

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.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • Thanks a lot for answer. It's my fall. I tried to find answer docs.python.org but not find. Sorry for this very simple question. – maxsocl Apr 17 '12 at 13:06