1
#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.

DanielTheRocketMan
  • 3,199
  • 5
  • 36
  • 65

2 Answers2

4

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
C_Z_
  • 7,427
  • 5
  • 44
  • 81
1

Writing old = myList does not bind the two variables inextricably; it assigns the value of myList to old at that point in time. By reassigning myList to a new list afterwards, you are then making myList and old point to different values.

Jack Taylor
  • 5,588
  • 19
  • 35