Derek_Y
Derek_Y

Reputation: 47

The rules of list references?

I got really confused on the list reference in python. Please help me understand. a simple case as below:

arr1 = []
arr2 = [1, 2]
arr1.append(arr2)
#arr2[0] = 5
arr2 = [6]
print(arr1)

So after append arr2 to arr1 without deep copy, to my understanding any change on arr2 would be reflected in arr1. However, only changing components like arr2[0] = 5 updates the arr1, while arr2 = [6] won't. Any reason why?

Upvotes: 0

Views: 61

Answers (2)

S.B
S.B

Reputation: 16476

to my understanding any change on arr2 would be reflected in arr1

This is true for mutation, but assigning a new object to a label does not mutate the object, you are going to create a new list object [6] in memory and assign it to that label. arr2 now points to this new object(with different id()) not the one stored in arr1.

List objects are mutable so you can mutate them with lets say .append() method. In this case, any change to arr2 using .append() will reflect the list stored in arr1

arr1 = []
arr2 = [1, 2]
arr1.append(arr2)

arr2.append(6)
print(arr1)

Anytime you want to check if they are the same objects or not, simply print ids before and after. In case of mutation:

print(id(arr1[0])) # 2157378023744
print(id(arr2))    # 2157378023744

Upvotes: 1

DocDriven
DocDriven

Reputation: 3974

When you execute arr2 = [6], you create a new list object that is now referenced by arr2. The reference in the list still points to the initial list, so you cannot use the label arr2 anymore to change the contents of the list referenced in arr1.

Upvotes: 1

Related Questions