Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
Vexoids Avatar asked Apr 21 '26 04:04

Vexoids


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!