Mutability of lists in python
<p>Example one: Changing the value that has been appended to b changes the value in the original list l</p>

<pre><code>&gt;&gt;&gt; l = [1 , 2, 3]
&gt;&gt;&gt; b = []
&gt;&gt;&gt; b.append(l)
&gt;&gt;&gt; b[0].append(4)
&gt;&gt;&gt; b
[[1, 2, 3, 4]]
&gt;&gt;&gt; l
[1, 2, 3, 4]
</code></pre>

<p>Example 2: l1 is appended to ans and then the value of l1 is modified. However, the value in ans remains the same.</p>

<pre><code>&gt;&gt;&gt; l1 = [1, 2, 3]
&gt;&gt;&gt; ans = []
&gt;&gt;&gt; ans.append(l1)
&gt;&gt;&gt; ans
[[1, 2, 3]]
&gt;&gt;&gt; l1 = [2, 3, 4]
&gt;&gt;&gt; ans
[[1, 2, 3]]
</code></pre>

<p>I seem to be missing some fundamental point about the mutability of lists. Could someone please point it out?</p>

<p>In your first example, <code>l</code> is a pointer, as well as <code>b</code>.</p>

<p><code>l</code> is then appended to b, so <code>b[0]</code> now refers to the pointer.</p>

<p>Next, you append 4 to <code>b[0]</code>, which is the same thing as <code>l</code>, so 4 is added to both <code>b[0]</code> <em>and</em> <code>l</code>.</p>

<hr>

<p>In your second example, <code>ans</code> contains the pointer of <code>l1</code>, just like <code>b</code> contained the pointer of <code>l</code></p>

<p>Then, you changed <code>l1</code> itself by assigning it to a different array, so <code>l1</code> changed but <code>ans[0]</code> did not.</p>

<hr>

<p>The biggest takeaway from this is that <code>append</code> just changes the list, and the pointer remains the same. But when you set a variable to a different list, the pointer changes.</p>

python list mutable