In the first example, you are modifying the list referenced by B
.
Doing:
B[0] = 'shrubbery'
tells Python to set the first item in the list referenced by B
to the value of 'shrubbery'
. Moreover, this list happens to be the same list that is referenced by A
. This is because doing:
B = A
causes B
and A
to each refer to the same list:
>>> A = ['spam']
>>> B = A
>>> A is B
True
>>>
So, any changes to the list referenced by B
will also affect the list referenced by A
(and vice-versa) because they are the same object.
The second example however does not modify anything. Instead, it simply reassigns the name B
to a new value.
Once this line is executed:
B = 'dog'
B
no longer references the string 'string'
but rather the new string 'dog'
. The value of A
meanwhile is left unchanged.