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>Well, I can explain. Your <code>p</code> keeps reference to <code>q</code> and you cannot change that. That's all. So if you will edit <code>p[1]</code>, then basically it modifies <code>q</code>, because going there through reference.</p>

<p><strong>Any document can help understand the above behaviour?</strong>
<a href="https://docs.python.org/2/reference/datamodel.html" rel="nofollow">https://docs.python.org/2/reference/datamodel.html</a></p>

<p><strong>I have no idea why python did this?</strong> </p>

<p>To have two ways of doing things. 
Based on reference to object (you don't pass a copy of <code>q</code> to <code>p</code>, just only reference):</p>

<pre><code>&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']
</code></pre>

<p>and without (you pass a copy of <code>q</code> to <code>p</code>, not reference):</p>

<pre><code>&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]
</code></pre>

<p><strong>In which cases, this behaviour will happen?</strong></p>

<p>I think example above shows it.</p>

python