Reputation: 11
I have this snippet of code:
list1 = [1, 2, 3]
list2 = list1
list1 = [4, 5, 6]
print(list2)
print(list1)
Which results in the following output:
[1, 2, 3]
[4, 5, 6]
Why is list2
not still pointed to [4, 5, 6]
? I was under the impression that, since lists are mutable, the change would affect both list1
and list2
, since in RAM both lists are pointed to the same sequence of items.
Any explanation would be appreciated.
Upvotes: 1
Views: 152
Reputation: 52071
I have added the reason as comments in the code :
# list1 variable points to the memory location containing [1, 2, 3]
list1 = [1, 2, 3]
# list2 variable made to point to the memory location pointed to by list1
list2 = list1
# list1 variable made to point to the memory location containing
# a new list [4, 5, 6], list2 still pointing to [1, 2, 3]
list1 = [4, 5, 6]
print(list2) # list2 prints [1, 2, 3]
print(list1) # list1 prints [4, 5, 6]
Upvotes: 4
Reputation: 122024
Lists are mutable. However, the line:
list1 = [4, 5, 6]
does not mutate the list object previously referenced by list1
, it creates a brand new list object, and switches the list1
identifier to reference the new one. You can see this by looking at object IDs:
>>> list1 = [1, 2, 3]
>>> list2 = list1
>>> id(list1)
4379272472
>>> id(list2)
4379272472 # both reference same object
>>> list1 = [4, 5, 6]
>>> id(list1)
4379279016 # list1 now references new object
>>> id(list2)
4379272472 # list2 still references previous object
Upvotes: 3
Reputation: 21893
I'll go through the lines one by one:
# Define a list [1, 2, 3] and save it into list1 variable
list1 = [1, 2, 3]
# Define list2 to be equal to list1 (that is, list2 == list1 == [1, 2, 3])
list2 = list1
# Create a new list [4, 5, 6] and save it into list1 variable
# Notice, that this replaces the existing list1!!
list1 = [4, 5, 6]
# Print list2, which still points to the original list [1, 2, 3]
print(list2)
# Print the new list1, [4, 5, 6] that is
print(list1)
However, this:
list1 = [1, 2, 3]
list2 = list1
list1.append(4)
print(list2)
print(list1)
Will output:
[1, 2, 3, 4]
[1, 2, 3, 4]
Since we are editing the list1
(and therefore list2
, they are mutable), not creating a new list and saving it under the variable name list1
The keyword here is create a new list, so you're not editing list1
in your example, you're actually changing the name list1
to point to a whole different list.
Upvotes: 3