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>It's tricky, but when you multiply a list, you are creating a new list.</p>

<pre><code>l = [1, 5, 9, 3]
h = l
</code></pre>

<p>'l' and 'h' are now referring to the same list in memory.</p>

<pre><code>h[0], h[2] = h[2], h[0]

print(h)  # [9, 5, 1, 3]
print(l)  # [9, 5, 1, 3]
</code></pre>

<p>You swapped the values in <code>h</code>, so the values are changed in <code>l</code>.  This makes sense when you think about them as different names for <em>the same object</em></p>

<pre><code>h = h * 2

print(h)  # [9, 5, 1, 3, 9, 5, 1, 3]
print(l)  # [9, 5, 1, 3]
</code></pre>

<p>When multiplying <code>h * 2</code>, you are creating a <em>new list</em>, so now only <code>l</code> will be the original list object.</p>

<pre><code>&gt;&gt;&gt; l = [1, 5, 9, 3]
&gt;&gt;&gt; h = l
&gt;&gt;&gt; id(h) == id(l)
True
&gt;&gt;&gt; id(h)
139753623282464
&gt;&gt;&gt; h = h * 2
&gt;&gt;&gt; id(h) == id(l)
False
&gt;&gt;&gt; id(h)
139753624022264
</code></pre>

<p>See how the <code>id</code> of <code>h</code> changes after the multiplication?  The <code>*</code> operator creates a new list, unlike other list operation, such as <code>append()</code> which alter the current list.</p>

<pre><code>&gt;&gt;&gt; h.append(1000)
&gt;&gt;&gt; id(h)
139753623282464    # same as above!
</code></pre>

<p>Hope this helps!</p>

python pointers