Note that there are some explanatory texts on larger screens.

plurals
  1. POMultiply operator applied to list(data structure)
    text
    copied!<p>I'm reading <a href="http://openbookproject.net/thinkCSpy/" rel="noreferrer">How to think like a computer scientist</a> which is an introductory text for "Python Programming".</p> <p>I want to clarify the behaviour of multiply operator (<code>*</code>) when applied to lists.</p> <p>Consider the function <strong>make_matrix</strong></p> <pre><code>def make_matrix(rows, columns): """ &gt;&gt;&gt; make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] &gt;&gt;&gt; m = make_matrix(4, 2) &gt;&gt;&gt; m[1][1] = 7 &gt;&gt;&gt; m [[0, 0], [0, 7], [0, 0], [0, 0]] """ return [[0] * columns] * rows </code></pre> <p>The actual output is </p> <pre><code>[[0, 7], [0, 7], [0, 7], [0, 7]] </code></pre> <p>The correct version of <strong>make_matrix</strong> is :</p> <pre><code>def make_matrix(rows, columns): """ &gt;&gt;&gt; make_matrix(3, 5) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] &gt;&gt;&gt; make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] &gt;&gt;&gt; m = make_matrix(4, 2) &gt;&gt;&gt; m[1][1] = 7 &gt;&gt;&gt; m [[0, 0], [0, 7], [0, 0], [0, 0]] """ matrix = [] for row in range(rows): matrix += [[0] * columns] return matrix </code></pre> <p>The reason why first version of <strong>make_matrix</strong> fails ( as explained in the book at 9.8 ) is that</p> <p><em>...each row is an alias of the other rows...</em></p> <p>I wonder why </p> <pre><code>[[0] * columns] * rows </code></pre> <p>causes <em>...each row is an alias of the other rows...</em></p> <p>but not </p> <pre><code>[[0] * columns] </code></pre> <p>i.e. why each <code>[0]</code> in a row is not an alias of other row element.</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