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>If you are new to Python you may run into issues like this.</p>

<p>In Python if you say </p>

<pre><code>    a = [10]
</code></pre>

<p>And then say </p>

<pre><code>    b = a
</code></pre>

<p>What happens? b gets the value of a, but also any change in a will make the similar change in b, because instead of just copying the value "b" is pointed towards "a" (that means changes in a will reflect in b as well)
That is the reason why you are facing that issue.</p>

<p>In case you don't want this you can use copy module in python </p>

<pre><code>    from copy import copy

    b = copy(a)
</code></pre>

<p>Now even though you change the value of "a", "b" value will be same.</p>

<p><a href="http://www.python-course.eu/deep_copy.php" rel="nofollow">For any reference regarding the same topic</a> </p>

python