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><code>each[:]</code> creates a <em>shallow</em> copy of each nested list. <code>copy.deepcopy()</code> would make a <em>deep</em> copy.</p>

<p>In this specific case, where your nested lists contain immutable integers, this difference doesn't actually matter; <code>deepcopy()</code> returns the integer unchanged when copying. But if there were <em>mutable</em> objects in the nested lists, then <code>deepcopy()</code> would continue to create copies of those, while your list comprehension would not.</p>

<p>For example, you'd see a difference when copying a list containing lists with with dictionaries:</p>

<pre><code>&gt;&gt;&gt; from copy import deepcopy
&gt;&gt;&gt; sample = [[{'foo': 'bar'}, {'ham': 'spam'}], [{'monty': 'python'}, {'eric': 'idle'}]]
&gt;&gt;&gt; shallow = [each[:] for each in sample]
&gt;&gt;&gt; deep = deepcopy(sample)
&gt;&gt;&gt; sample[-1][-1]['john'] = 'cleese'
&gt;&gt;&gt; sample
[[{'foo': 'bar'}, {'ham': 'spam'}], [{'monty': 'python'}, {'eric': 'idle', 'john': 'cleese'}]]
&gt;&gt;&gt; shallow
[[{'foo': 'bar'}, {'ham': 'spam'}], [{'monty': 'python'}, {'eric': 'idle', 'john': 'cleese'}]]
&gt;&gt;&gt; deep
[[{'foo': 'bar'}, {'ham': 'spam'}], [{'monty': 'python'}, {'eric': 'idle'}]]
</code></pre>

<p>Because the <code>deepcopy()</code> operation has to test each element in the nested lists, it is also slower; the list comprehension is the better option if you know that you don't need to produce a 'deeper' copy.</p>

python list copy deep-copy