Search code examples
pythonlistequals

Shared References and Equality


Using Python 3.4 and working through examples in a book by O'Reily. The example shows:

A = ['spam']
B = A
B[0] = 'shrubbery'

Result after running print A:

'shrubbery'

Now my thought process is thatA was defined but never changed.

This example yields a different result

A = 'string'
B = A
B = 'dog'

This is the result after running print A:

'string'

Can someone explain?


Solution

  • 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.