Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>EVERYTHING in python are objects, and python never makes copies unless explicity asked to do so.</p> <p>When you do </p> <pre><code>innerList = [0] * 10 </code></pre> <p>you create a list with 10 elements, <strong>all of them refering to the same <code>int</code> object <em><code>0</code></em></strong>.</p> <p>Since integer objects are <strong>immutable</strong>, when you do</p> <pre><code>innerList[1] = 15 </code></pre> <p>You are changing the second element of the list so that it refers to another integer <em><code>15</code></em>. That always works because of <em><code>int</code></em> objects immutability.</p> <p>That's why</p> <pre><code>outerList = innerList * 5 </code></pre> <p>Will create a <code>list</code> object with 5 elements, each one is a reference to <strong>the same <code>innerList</code></strong> just as above. But since <code>list</code> objects are <strong>mutable</strong>:</p> <pre><code>outerList[2].append('something') </code></pre> <p>Is the same as:</p> <pre><code>innerList.append('something') </code></pre> <p>Because they are two references to the <strong>same <code>list</code> object</strong>. So the element ends up in that single <code>list</code>. It appears to be duplicated, but the fact is that there is only one <code>list</code> object, and many references to it.</p> <p>By contrast if you do</p> <pre><code>outerList[1] = outerList[1] + ['something'] </code></pre> <p>Here you are <strong>creating <em>another</em> <code>list</code> object</strong> (using <code>+</code> with lists is an explicit copy), and assigning a reference to it into the second position of <code>outerList</code>. If you "append" the element this way (not really appending, but creating another list), <code>innerList</code> will be unaffected.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload