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>When you build a list like this <code>[[0]*3]*3</code> you are creating 3 references to the same list, use a list comprehension instead:</p>

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

<p>See how in the comprehension here just the <code>[0][0]</code> is modified:</p>

<pre><code>&gt;&gt;&gt; l1 = [[0]*3]*3
&gt;&gt;&gt; l1[0][0] = 10
&gt;&gt;&gt; l1
[[10, 0, 0], [10, 0, 0], [10, 0, 0]]
&gt;&gt;&gt; l2 = [[0 for _ in xrange(3)] for _ in xrange(3)]
&gt;&gt;&gt; l2[0][0] = 10
&gt;&gt;&gt; l2
[[10, 0, 0], [0, 0, 0], [0, 0, 0]]
</code></pre>

python list matrix