Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: When do two variables point at the same object in memory?

Here is an example:

l = [1, 5, 9, 3]
h = l

h[0], h[2] = h[2], h[0]

print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]

h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]

My understanding was that calling setting h = l would simply point h at the same item in memory that l was pointing at. So why is it that in the last 3 lines, h and l don't give the same results?

like image 444
TheRealFakeNews Avatar asked Aug 26 '16 18:08

TheRealFakeNews


People also ask

Can multiple variable reference a same object in memory?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.

How do you check if two variables are pointing to the same object Python?

The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.

Can two variables have the same memory address?

You can not have 2 variables at the same address, the standard specifically mandates against this. You can not change the address of an object once it has been assign by the compiler.

How does Python allocate memory for variables?

Python optimizes memory utilization by allocating the same object reference to a new variable if the object already exists with the same value. That is why python is called more memory efficient.


2 Answers

That's quite simple to check, run this simple test:

l = [1, 5, 9, 3]
h = l

h[0], h[2] = h[2], h[0]

print(h)  # [9, 5, 1, 3]
print(l)  # [9, 5, 1, 3]

print id(h), id(l)
h = h * 2
print id(h), id(l)

print(h)  # [9, 5, 1, 3, 9, 5, 1, 3]
print(l)  # [9, 5, 1, 3]

As you can see because of the line h = h * 2, the h's id has been changed

Why is this? When you're using * operator it creates a new list (new memory space). In your case this new list is being assigned to the old h reference, that's why you can see the id is different after h = h * 2

If you want to know more about this subject, make sure you look at Data Model link.

like image 152
BPL Avatar answered Oct 08 '22 19:10

BPL


The assignment does make h point to the same item as l. However, it does not permanently weld the two. When you change h with h = h * 2, you tell Python to build a doubled version elsewhere in memory, and then make h point to the doubled version. You haven't given any instructions to change l; that still points to the original item.

like image 33
Prune Avatar answered Oct 08 '22 19:10

Prune