<pre><code>y = list(x)
</code></pre>
<p>上面的语句创建列表<code>x</code>的浅层副本。你知道吗</p>
<p>从<a href="https://docs.python.org/2/library/copy.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.</p>
</blockquote>
<p>在这里,您确实获得了一个新对象<code>y</code>,但是由于其中的列表是一个可变对象,因此您获得了对原始对象的引用。而且,如果继续创建这些浅层副本,列表对象将在所有副本之间共享。你知道吗</p>
<p>您可以使用<code>id</code>检查它:</p>
<pre><code>>>> id(x)
140183460314288
>>> id(y)
140183460372992 # this is different from y
>>> id(x[1])
140183460314864
>>> id(y[1]) # this is same as x[1]
140183460314864
>>> y1 = list(y) # another shallow copy from y
>>> id(y1[1])
140183460314864 # this is still same
</code></pre>
<p>如果预期的行为确实需要修改<code>y</code>的内容而不影响<code>x</code>,则需要执行<code>deepcopy</code>:</p>
<pre><code>>>> >>> from copy import deepcopy
>>> z = deepcopy(x)
>>> id(z[1])
140183460405400 # this is different now because of deepcopy
</code></pre>
<p>您可以看到这个id与<code>id(x[1])</code>不同,现在如果您尝试修改内容,它们将不会反映在<code>x</code>。你知道吗</p>