Python non-numpy matrixes issue
<p>I have the following issue:</p>

<p>I have a list of lists with the following declaration:</p>

<pre><code>As = [[0]*3]*3
</code></pre>

<p>I then try to change the values of this "matrix" with this:</p>

<pre><code>for i in range(3):
    for j in range(3):
        As[i][j] = calculate(A, i, j)*((-1)**(i+j))
</code></pre>

<p>As you may have guessed, this is used in calculating the inverse of a 3x3 matrix.</p>

<p>The function calculate returns the following values:</p>

<pre><code>4.0     
-2.0    
-3.0    
-4.0    
-10.0   
9.0     
4.0     
10.0    
-21.0   
</code></pre>

<p>However, As has the following value:</p>

<p><code>[[4.0, -10.0, -21.0], [4.0, -10.0, -21.0], [4.0, -10.0, -21.0]]</code>, which is unexpected.</p>

<p>What am I missing?</p>

<p>The problem is in your first line:</p>

<pre><code>As = [[0]*3]*3
</code></pre>

<p>This is equivalent to the following:</p>

<pre><code>a = [0] * 3
As = [a] * 3
</code></pre>

<p><code>As</code> therefore contains three references to the same list:</p>

<pre><code>&gt;&gt;&gt; for a in As:
...     print(id(a))
...
4293437996
4293437996
4293437996
</code></pre>

<p>So when you change this list, it's reflected in all of the rows of your matrix.</p>

<p>To get around this, you can use a list comprehension to construct the outer list:</p>

<pre><code>As = [[0] * 3 for _ in xrange(3)]
</code></pre>

<p>Note that the inner list <code>[0] * 3</code> is fine, since the list contains only an integer, which is immutable.  It therefore doesn't matter that the list refers to the <em>same instance</em> of that integer, since they can't be changed.</p>

python list matrix