python: how to explain the following codes
<p>Tested on my local machine:</p>

<pre><code>Python 2.7.3 (default, Jun 22 2015, 19:33:41) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; q=[2,3]
&gt;&gt;&gt; p=[1,q,4]
&gt;&gt;&gt; p[1].append('test')
&gt;&gt;&gt; q
[2, 3, 'test']
&gt;&gt;&gt; hex(id(q))
'0x7fabfa5c2b90'
&gt;&gt;&gt; 
&gt;&gt;&gt; 
&gt;&gt;&gt; hex(id(p))
'0x7fabfa5c2b48'
&gt;&gt;&gt; hex(id(p[1]))
'0x7fabfa5c2b90'
&gt;&gt;&gt; 
&gt;&gt;&gt; 
&gt;&gt;&gt; p.append(q)
&gt;&gt;&gt; p
[1, [2, 3, 'test'], 4, [2, 3, 'test']]
&gt;&gt;&gt; p[1].append('test2')
&gt;&gt;&gt; p
[1, [2, 3, 'test', 'test2'], 4, [2, 3, 'test', 'test2']]
&gt;&gt;&gt; 
</code></pre>

<p>At beginning, I thought when generating p, a copy of q is copied into p. </p>

<p><strong>Any document can help understand the above behaviour? I have no idea why python did this? and In which cases, this behaviour will happen?</strong> </p>

<p>Thanks</p>

<p>When you append <code>q</code> to <code>p</code>, you are not creating a copy of <code>q</code>, you are actually appending a reference to the object that the name <code>q</code> currently points to.  Therefore, when you append to <code>q</code> (or in this case <code>p[1]</code>, which points to the same object), it will append to the single object that those two references point to.  If you want to insert a <em>copy</em> of <code>q</code>, you can use slicing like so:</p>

<pre><code>p=[1,q[:],4]
</code></pre>

<p>or</p>

<pre><code>p.append(q[:])
</code></pre>

<p>This will create a new anonymous list that you can append to without affecting the original or any other reference to that same object that <code>q</code> points to.</p>

<p>Here's an example:</p>

<pre><code>&gt;&gt;&gt; q = [2, 3]
&gt;&gt;&gt; p = [1, q[:], 4]      # include a copy of q using [:]
&gt;&gt;&gt; p[1].append('test')   # append to copy
&gt;&gt;&gt; p
[1, [2, 3, 'test'], 4]    # 'test' is in p[1]
&gt;&gt;&gt; q 
[2, 3]                    # but not in q
&gt;&gt;&gt; p = [1, q, 4]         # include q itself in p (no [:])
&gt;&gt;&gt; p[1].append('test')
&gt;&gt;&gt; p
[1, [2, 3, 'test'], 4]    # test appears in p[1]
&gt;&gt;&gt; q
[2, 3, 'test']            # and also in q
</code></pre>

<p>See the docs for lists <a class='doc-link' href="http://stackoverflow.com/documentation/python/209/list#t=20160825190558726918">here</a></p>

python