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.

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.