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 chang
This will work
col = 2
row = 3
[[0] * col for row in xrange(row)]
If the sizes involved are really only 2 and 3,
mat = [[0, 0], [0, 0], [0, 0]]
is easily best and hasn't been mentioned yet.
Is there anything itertools can't do? :)
>>> from itertools import repeat,izip
>>> rows=3
>>> cols=6
>>> A=map(list,izip(*[repeat(0,rows*cols)]*cols))
>>> A
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> A[0][3] = 2
>>> A
[[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
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)]
Try this:
>>> cols = 6
>>> rows = 3
>>> a = [[0]*cols for _ in [0]*rows]
>>> a
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> a[0][3] = 2
>>> a
[[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
This is also discussed in this answer:
>>> lst_2d = [[0] * 3 for i in xrange(3)]
>>> lst_2d
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> lst_2d[0][0] = 5
>>> lst_2d
[[5, 0, 0], [0, 0, 0], [0, 0, 0]]
I use
mat = [[0 for col in range(3)] for row in range(2)]
although depending on what you do with the matrix after you create it, you might take a look at using a NumPy array.