In Python, what's the difference between deepcopy and [each[:] for each in List]
<p>Below is the example code:</p>

<pre><code>from copy import deepcopy
List = [range(3), range(3), range(3)]
a = deepcopy(List)
b = [each[:] for each in List]
</code></pre>

<p>I know the time required to initialize a is slower than b's time, but why does this happen? What's the difference between deepcopy and  [each[:] for each in List]? Why is deepcopy so slow?</p>

<p>As Martijn Pieters said each[:] will perform by creating a shallow copy of each nested list. If your list elements are immutable objects then you can use this, otherwise you have to use deepcopy from copy module.</p>

<p>It's possible to completely copy shallow list structures with the slice operator without having any of the side effects, have a look to the following snapshot:</p>

<pre><code>LIST_1 = ['A','B',['AB','BA']]
print LIST_1
&gt;&gt;&gt; ['A', 'B', ['AB', 'BA']]
LIST_2= LIST_1[:]
print id(LIST_1)
&gt;&gt;&gt; 40427648
print id(LIST_2)
&gt;&gt;&gt; 50932872  
LIST_2[2][1] = "D"
LIST_2[2][0] = "C";

print LIST_2
&gt;&gt;&gt; ['A', 'B', ['C', 'D']] 
print LIST_1
&gt;&gt;&gt; ['A', 'B', ['C', 'D']] 
</code></pre>

<p>However in deepcopy method:</p>

<p>A solution to the described problems is to use the module "copy". This module provides the method "copy", which allows a complete copy of a arbitrary list, i.e. shallow and other lists. so you use <code>copy.deepcopy(...)</code> for deep copying a list:</p>

<pre><code>deepcopy(x, memo=None, _nil=[])
</code></pre>

<p>The following script uses our example above and this method: </p>

<pre><code>from copy import deepcopy

LIST_1 = ['A','B',['AB','BA']]

LIST_2= deepcopy(LIST_1)

LIST_2[2][1] = "D"
LIST_2[0] = "C";

print LIST_2
&gt;&gt;&gt;['C', 'B', ['AB', 'D']]
print LIST_1
&gt;&gt;&gt;['A', 'B', ['AB', 'BA']]
</code></pre>

<p><a href="https://i.stack.imgur.com/wPphj.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/wPphj.jpg" alt="enter image description here"></a></p>

<p>Therefore, a shallow copy of each nested list does not recursively makes copies of the inner objects. It only makes a copy of the outermost list, while still referencing the inner lists from the previous variable and that's why deepcopy is slower.</p>

python list copy deep-copy