Variable creation process in Python
<p>Doing everything in Microsoft shell and using 2.7.12</p>

<h1>Prelude</h1>

<pre><code>a = [1,2,3,4,5]
b = [1,2,3,4,5]
c = a
</code></pre>

<h1>Actions</h1>

<pre><code>a[0] is b[0] is c[0]
True
</code></pre>

<p>Are not the three lists pointing to the same elements in the memory location? and are therefore liable to change if one is changed?</p>

<p>Part I understand:</p>

<pre><code>c[0] = 8888888
a[0]
8888888
</code></pre>

<p>Part I don't understand:</p>

<pre><code>b[0] = 9999999
a[0]
1
</code></pre>

<p>Python can decide to share immutable objects storage (strings, integers, ...)</p>

<p>Since they are immutable, it is transparent to the user. It just saves memory.</p>

<pre><code>a[0] is b[0]
</code></pre>

<p>could be True or False. On the other hand</p>

<pre><code>a[0] is c[0]
</code></pre>

<p>is always True because <code>a is c</code>. (and modifying <code>a</code> changes <code>c</code>)</p>

<p>But since <code>list</code> type is mutable, <code>a</code> cannot be <code>b</code> (Python doesn't allow itself to optimize storage in that case). Those are independent objects. Modifying <code>a</code> cannot change <code>b</code>.</p>

<p>note about my "can be true or false" remark. Consider this in python 3.4</p>

<pre><code>&gt;&gt;&gt; b=1234567890
&gt;&gt;&gt; a=[1234567890]
&gt;&gt;&gt; b is a[0]
False
</code></pre>

<p>Python did not bother to make the link between <code>b</code> and <code>a[0]</code>. Also happens with long strings (I assume that would be a performance issue vs low probability to find an exact big number 2 times in a row? whereas <code>1</code> has better chance to be repeated throughout the program)</p>

<p>However if you do this you get a different result:</p>

<pre><code>&gt;&gt;&gt; b=1234567890
&gt;&gt;&gt; a=[b,1,2]
&gt;&gt;&gt; b is a[0]
True
</code></pre>

<p>(I wouldn't say for sure why as it can vary depending whether it is stored as a long int or mere int, value or address, etc... , but Python has definitely more information about the value being duplicated here!)</p>

<p>Conclusion is: don't rely on that for immutable objects. Use <code>==</code> at all times.</p>

python arrays python-2.7