Reputation: 2923
Whats the most efficient way to initialize a matrix in Python without using numpy. For example I'd like to create:
matrix = [
[[0,0],[0,0],[0,0]]
[[0,0],[0,0],[0,0]]
[[0,0],[0,0],[0,0]]
]
I was creating one using:
dpcols = [[0,0]] * len(matrix[0])
matrix = [dpcols] * len(matrix)
But with this, if i change
matrix[1][1] = [1,1]
Then indexes [0][1], [1][1], and [2][1] all gets changed to [1,1], due to them all being linked together.
Upvotes: 1
Views: 862
Reputation: 4548
I don't think this is as efficient as numpy since it's a double for loop, but it's easy to write:
>>> rows,cols = 2,3
>>> a = [[[0,0] for c in range(cols)] for r in range(rows)]
>>> a
[[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]
>>> a[1][1] = [1,1]
>>> a
[[[0, 0], [0, 0], [0, 0]], [[0, 0], [1, 1], [0, 0]]]
Upvotes: 4