[Python] Reference list object by a variable is different than for (some) other objects?

Discussão em 'Python' iniciado por Stack, Janeiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    In defining variable of a list object, for example:

    x = [1,2,0.2,3,4]
    y = x
    x.sort()


    I would expect that y is still equal to [1, 2, 0.2, 3, 4], but it does not. The value of y changed as x changed. To counter this, I found that using y = x.copy() can preserve the value in the first line.

    On the other hand, another example :

    x = 5
    y = x
    x = 4


    from this the value of y is still 5, it does not change as x change.

    My question : is this due to the design in list's class, or there is another explanation? I found the dynamic change also happen when using x.append(value). Any insight is appreciated. Regards, Arief

    Continue reading...

Compartilhe esta Página