Lists in Python as stored by reference.
This means that when you do list2 = list1
, you are not making a copy of the list - you are merely saying "list2
refers to the same thing list1
does," namely, the list you originally created when you did list1 = []
.
Python specifies +=
to mean "append in place" for lists, because most of the time when you're using +=
on lists, that's what you want to do - you usually don't want to create new lists every single time you add an element.
Thus, when you append to list2
, which "refers to the same object list1
does," and then read from list1
, you see the appended item, as is expected since both of them point at the same list.
With +
, however, a new list is always created because it doesn't make sense to modify either of the operands in place (since a+b
doesn't imply the modification of a
or b
).
Therefore, when you do list2 = list2 + [1]
, you create a new list that has all of the contents of the original object pointed to by list2
and also 1
, and then say that list2
now references that new list. Since it now references a different list than list1
does, when you go to read from list1
you still see the original list without the extra 1
.