Search code examples
pythonlistpass-by-reference

Changing lists in Python


#Case 1
myList=[1,2,3,4]
old=myList
myList=[5,6,7,8]
print(old)

#Case 2
myList=[1,2,3,4]
old=myList
myList[0]=10
print(old)

#Case 3
myList=[1,2,3,4]
old=myList.copy()
myList[0]=10
print(old)

[1, 2, 3, 4]
[10, 2, 3, 4]
[1, 2, 3, 4]

For me the case 3 is the safe case and Case 2 is clear. However, I am not able to clearly understand why in case 1 old is not changed.


Solution

  • In case 1, we are re-assigning a brand new list to the name myList. The original list that was assigned to myList is not affected by this operation; myList is now simply pointing to a different object

    This becomes clear when we look at the ids of the objects:

    >>> myList = [1,2,3,4]
    >>> print(id(myList))
    47168728
    >>> old = myList
    >>> print(id(old))
    47168728
    >>> myList = [5,6,7,8]
    >>> print(id(myList))
    47221816
    >>> print(id(old))
    47168728