pythonpython-3.xmethods

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


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


Solution

  • Every variable is just a pointer to an Python object, if you have two variables pointing to the same object then you'll see the changes in each of them (and .sort works in-place, if you want a new list you should use x = sorted(x)). However if you re-assign a variable then it will point to a different object.


    I included some images to better visualize what's happening (not high-quality but I hope it conveys the message).

    x = [1,2,0.2,3,4]
    y = x
    

    enter image description here

    If you copy (it's a shallow copy so the list-contents still refer to the same items!):

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

    enter image description here

    Your second case is just the same:

    x = 5
    y = x
    

    enter image description here

    But then you re-assign the variable x (so it points to another object thereafter):

    x = 4
    

    enter image description here