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.