I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.
mat=[[0]*2]*3
However, when I change the value of one of the items in the matrix, it changes the value of that entry in every row, since the id of each row in mat
is the same. For example, after assigning
mat[0][0]=1
mat
is [[1, 0], [1, 0], [1, 0]]
.
I know I can create the Zero matrix using a loop as follows,
mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
but can anyone show me a more pythonic way?
Use a list comprehension:
>>> mat = [[0]*2 for x in xrange(3)]
>>> mat[0][0] = 1
>>> mat
[[1, 0], [0, 0], [0, 0]]
Or, as a function:
def matrix(rows, cols):
return [[0]*cols for x in xrange(rows)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With