[Python] Is Python list variable not passing by reference?

Discussão em 'Python' iniciado por Stack, Abril 8, 2025.

  1. Stack

    Stack Membro Participativo

    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]

    Continue reading...

Compartilhe esta Página