Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>multiplying a single reference data type would simply create multiple references of the same type. What it means is that [True]*N is actually N times the same instance of the element [True]</p> <p>Thus changing one would inadvertently change the others </p> <p>As you can see in the following example, </p> <pre><code>&gt;&gt;&gt; grid = [[True]]*10 &gt;&gt;&gt; grid = [True]*10 &gt;&gt;&gt; [id(e) for e in grid] [505379788, 505379788, 505379788, 505379788, 505379788, 505379788, 505379788, 505379788, 505379788, 505379788] </code></pre> <p>It shows all the elements are actually the same instance.</p> <p>But because here as the element is not a mutable Type, changing won't be an issue here as, changing one of the element would simply assign a new instance.</p> <p>Problem happens with a mutable type</p> <pre><code>&gt;&gt;&gt; [id(e) for e in grid] [66523744, 66523744, 66523744, 66523744, 66523744, 66523744, 66523744, 66523744, 66523744, 66523744] &gt;&gt;&gt; grid[0][0]=False &gt;&gt;&gt; [id(e) for e in grid] [66523744, 66523744, 66523744, 66523744, 66523744, 66523744, 66523744, 66523744, 66523744, 66523744] &gt;&gt;&gt; grid [[False], [False], [False], [False], [False], [False], [False], [False], [False], [False]] </code></pre> <p>To get over it, you need to understand which are mutable types and refrain from duplicating it but instead create new multiple instances of the same mutable types</p> <p>So here as a list is a mutable type, you need to create multiple instances, possibly through list comprehension</p> <pre><code>[[False]*N for _ in range(N)] </code></pre>
 

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