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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With