I'm confused with the pass-by-ref and pass-by-value in Python.
In the following code, when listB = listA, listB should being assigned the pointer (reference) to the list in ListA variable. Any changes to listB should be reflected on listA. However, that is not the case in my test. Am I doing something wrong with the code? I'm running Python 3.4.3
>>> listA = [1,2,3]
>>> listB = listA
>>> listA = [4,5,6]
>>> print(listA, listB)
[4, 5, 6] [1, 2, 3]
>>> listB[0] ='new'
>>> print(listA, listB)
[4, 5, 6] ['new', 2, 3]
You're reassigning listA altogether, so there is no relation between it and listB.
For example:
listA = [2,2,3]
listB = listA
id(listA)
Out[6]: 90404936
id(listB)
Out[7]: 90404936
listA[0]=2
id(listA)
Out[9]: 90404936
listB
Out[10]: [2, 2, 3]
But then when you reassign listA you lose that id:
listA = [3,3,3]
id(listA)
Out[12]: 92762056
But listB stays at the same id:
id(listB)
Out[13]: 90404936
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With