Search code examples
pythonlistelementimmutabilitymutability

Changing elements of a list affects/does not affect a derived list


I do not understand the following anomalous behavior with lists in Python, and would appreciate it if someone could throw some light:

Snippet 1:

myList = [1,2,3,4]
A = [myList]*3
print(A)
myList[2]=45
print(A)

Output:

[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
[[1, 2, 45, 4], [1, 2, 45, 4], [1, 2, 45, 4]]

This makes sense to me, since we did not perform an additional copy function to 'shield' A from element operations on myList.

Snippet 2:

myList = [1,2,3,4]
A = myList*3
print(A)
myList[2]=45
print(A)

Output:

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

Why is a change to myList not reflected in A?


Solution

  • In the first case, you're duplicating 3 references to myList directly. In the second case, you're duplicating 3 references to the contents of myList, which leaves you with no connection to the original myList.