Search code examples
pythonlistandroid-listviewmutableprimitive-types

Python List mutable


I am trying to use Python term to explain why the following happens, can somebody explain why tmp becomes to [[1,2,3]] not stay as [[1,2]]?

arr = []
tmp = [1,2]
arr.append(tmp)
print arr # [[1,2]]
tmp.append(3)
print arr # [[1,2,3]]

Solution

  • arr = [] is an empty list, and when you append tmp to it via:

    tmp = [1, 2]
    arr.append(tmp)
    

    You are putting tmp in the arr list, thus giving you arr = [tmp] which can be expanded to arr = [[1,2]]. But the neat thing here is that you maintain a reference to to the list, [1,2] via the temp variable. Thus, when you append temp you are appending the same list that is in arr.

    For a bit further clarification, just because you are appending tmp to arr doesn't mean that the resulting list [[1,2]] is all going to be one continuous block in memory. You are going to have the arr list and the first element of arr is going to be a pointer to the list tmp.