Python: Append a list to another list and Clear the first list
<p>So this just blew my mind. I am working on a python code where I create a list, append it to a master list and clear the first list to add some more elements to it. When I clear the first list, even the master list gets cleared. I worked on a lot of list appends and clears but never observed this.</p>

<pre><code>list1 = []
list2 = []
list1 = [1,2,3]
list2.append(list1)
list1
[1, 2, 3]
list2
[[1, 2, 3]]
del list1[:]
list1
[]
list2
[[]]
</code></pre>

<p>I know this happens with appending dictionaries but I did not know how to deal with lists. Can some one please elaborate?</p>

<p>I am using Python2.7</p>

<p>Passing a <code>list</code> to a method like <code>append</code> is just passing a <em>reference</em> to the same <code>list</code> referred to by <code>list1</code>, so that's what gets appended to <code>list2</code>. They're still the same <code>list</code>, just referenced from two different places.</p>

<p>If you want to cut the tie between them, either:</p>

<ol>
<li>Insert a copy of <code>list1</code>, not <code>list1</code> itself, e.g. <code>list2.append(list1[:])</code>, or</li>
<li>Replace <code>list1</code> with a fresh <code>list</code> after <code>append</code>ing instead of clearing in place, changing <code>del list1[:]</code> to <code>list1 = []</code></li>
</ol>

<p>Note: It's a little unclear, but if you want the <em>contents</em> of <code>list1</code> to be added to <code>list2</code> (so <code>list2</code> should become <code>[1, 2, 3]</code> not <code>[[1, 2, 3]]</code> with the values in the nested <code>list</code>), you'd want to call <code>list2.extend(list1)</code>, not <code>append</code>, and in that case, no shallow copies are needed; the values from <code>list1</code> at that time would be individually <code>append</code>ed, and no further tie would exist between <code>list1</code> and <code>list2</code> (since the values are immutable <code>int</code>s; if they were mutable, say, nested <code>list</code>s, <code>dict</code>s, etc., you'd need to copy them to completely sever the tie, e.g. with <a href="https://docs.python.org/3/library/copy.html#copy.deepcopy" rel="nofollow"><code>copy.deepcopy</code></a> for complex nested structure).</p>

python list