Python: When do two variables point to 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 setting the call to h = l would just point h to the same element in memory that l pointing to. So why in the last three lines h and l do not give the same results?

+6
source share
5 answers

The assignment makes h a point for the same element as l . However, he does not weld two for long. When you change h to h = h * 2 , you tell Python to create a doubled version elsewhere in memory, and then make h doubled version. You did not indicate any indication of a change in l ; which still points to the source element.

+2
source

It is 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 , h id has been changed

Why is this? When you use the * operator, it creates a new list (new memory space). In your case, this new list is assigned to the old link h, so you can see that the identifier is different from h = h * 2

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

+7
source

h = h * 2 assigns h to the new list object.

You might want to change 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] 
+4
source

At any time when you assign a variable, its identifier (memory address) usually changes - the only reason it has not changed is that you are assigned a value that it already held. So your statement h = h * 2 made h become a completely new object - one whose value was based on the previous value of h, but which actually has nothing to do with its identity.

+1
source

This is complicated, but when you multiply a list, you create a new list.

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

'l' and 'h' now refer to the same list in memory.

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

You changed the values ​​in h , so the values ​​changed in l . It makes sense when you think of them as different names for the same object.

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

When you multiply h * 2 you create a new list, so now only the original list object will be l .

 >>> l = [1, 5, 9, 3] >>> h = l >>> id(h) == id(l) True >>> id(h) 139753623282464 >>> h = h * 2 >>> id(h) == id(l) False >>> id(h) 139753624022264 

See how id of h changes after multiplication? The * operator creates a new list, unlike other list operations, such as append() , which modify the current list.

 >>> h.append(1000) >>> id(h) 139753623282464 # same as above! 

Hope this helps!

+1
source

All Articles