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>So basically here is what the code is doing:</p>

<h3>Before delete</h3>

<p><a href="http://i.stack.imgur.com/T41Sv.png" rel="nofollow"><img src="http://i.stack.imgur.com/T41Sv.png" alt="enter image description here"></a></p>

<h3>After deleting</h3>

<p><a href="http://i.stack.imgur.com/uuiDI.png" rel="nofollow"><img src="http://i.stack.imgur.com/uuiDI.png" alt="enter image description here"></a></p>

<p>In short, both lists names are pointing to the same list object.</p>

<p><a href="http://www.pythontutor.com/visualize.html#code=list1%20%3D%20%5B%5D%0Alist2%20%3D%20%5B%5D%0Alist1%20%3D%20%5B1,2,3%5D%0Alist2.append(list1%29%0Adel%20list1%5B%3A%5D&amp;cumulative=false&amp;curInstr=4&amp;heapPrimitives=false&amp;mode=display&amp;origin=opt-frontend.js&amp;py=2&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" rel="nofollow">code visualization source</a></p>

python list