Reference to an element in a list
<p>I am a little confused about how python deal with reference to an element in a list, considering these two examples:</p>

<p>First example:</p>

<pre><code>import random
a = [[1,2],[3,4],[5,6],[7,8]]
b = [0.1,0.2]
c = random.choice(a)
c[:] = b
print(a)
</code></pre>

<p>Second example:</p>

<pre><code>import random
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = 0.1
c = random.choice(a)
c = b
print(a)
</code></pre>

<p>In first example, the content in list a is changed; while in the second example, the content of list a is not changed. Why is that? </p>

<p>Let's start with the second case. You write</p>

<pre><code>c = random.choice(a)
</code></pre>

<p>so the name <code>c</code> gets bound to some element of a, then</p>

<pre><code>c = b
</code></pre>

<p>so the name <code>c</code> gets bound to some other object (the one to which the name <code>b</code> is referring - the float 0.1).</p>

<hr>

<p>Now to the first case. You start with</p>

<pre><code>c = random.choice(a)
</code></pre>

<p>So the name <code>c</code> gets bound to an object in <code>a</code>, which is a list itself. Then you write</p>

<pre><code>c[:] = b
</code></pre>

<p>which means, replace all items in the list bound to by the name <code>c</code>, by some other list. In fact, this is called <a href="http://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice">slice assignment</a>, and is basically syntactic sugar for calling a method of the object to which <code>c</code> is bound.</p>

<hr>

<p>The difference, then, is that in the first case, it doesn't just bind a name first to one object, then to another. It binds a name to a list, then uses this name to indirectly call a method of the list.</p>

python random