When I initialize a 2-dimensional matrix in the following way, the behavior is very strange to me.
In [1]: matrix = [[None] * 2] * 3
In [2]: matrix
Out[2]: [[None, None], [None, None], [None, None]]
In [3]: matrix[0][0] = 5
In [4]: matrix
Out[4]: [[5, None], [5, None], [5, None]]
I now know I should initialize it in the following way to avoid this strange behavior:
matrix = [[None for x in range(2)] for x in range(3)]
Can someone explain why in the former case I am getting values duplicated across multiple arrays and is there benefit to this behavior?