Python: When do two variables point at the same object in memory?
<p>Here is an example:</p>

<pre><code>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]
</code></pre>

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

<p>That's quite simple to check, run this simple test:</p>

<pre><code>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]
</code></pre>

<p>As you can see because of the line <code>h = h * 2</code>, the h's id has been changed</p>

<p>Why is this? When you're using <code>*</code> operator it will be created 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 <code>h = h * 2</code></p>

<p>If you want to know more about this subject, make sure you look at <a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow">Data Model</a> link.</p>

python pointers