title: How to define matrices using * operator properly in python?
body: <p>I am trying to create an empty(only zeros) square matrix in a simple way. The first method that came to my mind is using the * operator:</p>
  <pre><code>size = 5
  matrix = [[0] * size] * size
  </code></pre>
  <p>When I try to assign some element of it, say, <code>matrix[0][0] = 1</code> I get such a matrix:</p>
  <blockquote>
  <p>[ [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0] ]</p>
  </blockquote>
  <p>I can see that * did not just create a new list but rather copied the reference of the initially created list 5 times. So, in order to make this somewhat presentable, I did the following:</p>
  <pre><code>size = 5
  matrix = []
  for _ in range(size):
      matrix.append([0] * size)
  matrix[0][0] = 1
  print(matrix)
  </code></pre>
  <p>Now the result is correct:</p>
  <blockquote>
  <p>[ [1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ]</p>
  </blockquote>
  <p><strong>Question</strong>: In the first code, when I initialized the matrix with * operator (<code>matrix = [[0] * size] * size</code>) assigning the first element would change all first elements of each row. But then I tried to modify entire row like this: <code>matrix[0] = [1, 0, 0, 0, 0]</code> which gave me the correct result. So what's the true way?</p>