Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List vs. int assignment - "Every variable is a pointer"

I know it's a very basic question, but I need help understanding this short concept.

I'm studying Python, and the book says "Every variable in Python is a pointer to an object. so when you write something like y=x you are infact making both of them point to the same object. If you change the original object, you will change every other pointer that points to it"

And then they give an example:

x=[1,2,3]
y=x
x[1]=3
print y

And it indeed prints [1,3,3]

However, when I wrote the following code:

x=5
y=x
x=7
print y

It does not print 7. It prints 5.

Why?

like image 723
Oria Gruber Avatar asked Oct 18 '25 13:10

Oria Gruber


1 Answers

Your first example can be explained as follows:

x=[1,2,3]  # The name x is assigned to the list object [1,2,3]
y=x        # The name y is assigned to the same list object referenced by x
x[1]=3     # This *modifies* the list object referenced by both x and y
print y    # The modified list object is printed

The second example however only reassigns the name x to a different integer object:

x=5      # The name x is assigned to the integer object 5
y=x      # The name y is assigned to the same integer object referenced by x
x=7      # The name x is *reassigned* to the new integer object 7
print y  # This prints 5 because the value of y was never changed

Here is a reference on assignment in Python.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!