Strange behavior of lists in python

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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x