Python - Elements of copy.copy() still share memory with the original one?
<p>I wanted to make a copy of a list (literally a separated clone that has nothing sharing with the original). I used copy.copy() and created 2 separated lists, but why does the elements of each copy still seem to share?</p>

<p>It's hard to explain, please check out the following output.</p>

<pre><code>&gt;&gt;&gt; a = [[0,1], [2,3]]
&gt;&gt;&gt; import copy
&gt;&gt;&gt; b = copy.copy(a)
&gt;&gt;&gt; temp = b.pop()
&gt;&gt;&gt; temp
[2, 3]
&gt;&gt;&gt; a
[[0, 1], [2, 3]]
&gt;&gt;&gt; b
[[0, 1]]
&gt;&gt;&gt; temp.append(4)
&gt;&gt;&gt; temp
[2, 3, 4]
&gt;&gt;&gt; a
[[0, 1], [2, 3, 4]]
&gt;&gt;&gt; b
[[0, 1]]
</code></pre>

<p>As you see, <strong>temp</strong> is popped from <strong>b</strong>, yet when I changed <strong>temp</strong> (aka append new stuff) then the data in <strong>a</strong> also changed.</p>

<p>My question is: Is this an expecting behavior of deepcopy? How can I make a totally separate copy of a list then?</p>

<p>P/S: As the above example, I guess I can do<br>
<code>temp = copy.copy(b.pop())</code><br>
but is this a proper way? Is there any other way to do what I want?</p>

<p>P/S 2: This also happens when I use b = a[:]</p>

<p>Thanks!</p>

<p>You should use deepcopy() there because the copy() makes shallow clone of the object that you are referencing not the object inside it.If you want the whole object(with the object inside it) use deepcopy() instead.</p>

<p>Please refer the links for better understanding</p>

<p><a href="http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy">What is the difference between a deep copy and a shallow copy?</a></p>

<p><a href="https://docs.python.org/2/library/copy.html" rel="nofollow">https://docs.python.org/2/library/copy.html</a></p>

python copy