Python: When do two variables point at the same object in memory?
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.
h = h * 2
assigns h
to a new list object.
You probably want to modify h
in-place:
h *= 2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3, 9, 5, 1, 3]