title: python 2D list transpose
body: <p>Given a matrix A, return the transpose of A.</p>
  <p>The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.</p>
  <p>Example
  Input: <code>[[1,2,3],[4,5,6]]</code></p>
  <p>Output: <code>[[1,4],[2,5],[3,6]]</code></p>
  <p>my code:</p>
  <pre><code>def transpose( A):
      length = len(A)
      width = len(A[0])
      res = [[0] * length] * width
      for i in range(length):
          for j in range(width):
              res[j][i] = A[i][j]
      return res
        
  transpose([[1,2,3],[4,5,6]])
  </code></pre>
  <p>my code's result :
  <code>[[3, 6], [3, 6], [3, 6]]</code></p>
  <p>I track in the double loop, every time the res is updated, the value of a column is updated.</p>
  <pre><code>def transpose( A):
      length = len(A)
      width = len(A[0])
      res = [[0] * length] * width
      for i in range(length):
          for j in range(width):
              res[j][i] = A[i][j]
              print(i,j,'-&gt;',j,i)
              print(res)
      return res
        
  transpose([[1,2,3],[4,5,6]])
  </code></pre>
  <p>The output information is as follows:</p>
  <pre><code>0 0 -&gt; 0 0
  [[1, 0], [1, 0], [1, 0]]
  0 1 -&gt; 1 0
  [[2, 0], [2, 0], [2, 0]]
  0 2 -&gt; 2 0
  [[3, 0], [3, 0], [3, 0]]
  1 0 -&gt; 0 1
  [[3, 4], [3, 4], [3, 4]]
  1 1 -&gt; 1 1
  [[3, 5], [3, 5], [3, 5]]
  1 2 -&gt; 2 1
  [[3, 6], [3, 6], [3, 6]]
  </code></pre>
  <p>But the following code gets the correct result：</p>
  <pre><code>def transpose( A):
          length, width = len(A), len(A[0])
          res = [[0] * length for _ in range(width)]
          for r, row in enumerate(A):
              for c, val in enumerate(row):
                  res[c][r] = val
          return res
  
  transpose([[1,2,3],[4,5,6]])
  </code></pre>
  <p>It's confusing!Is there any difference between the two ways of loop？</p>
  <p>Is it caused by the underlying code optimization during compilation?</p>