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]
When you do listA = [4,5,6]
, the reference to listA
(that was assigned to listB
) no longer points to listA
, since you completely replaced listA
with a new list.
If you remove that line, you will find that it works as expected.