Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating lists of lists in a pythonic way

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?

like image 873
Alasdair Avatar asked May 28 '09 20:05

Alasdair


1 Answers

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)]
like image 148
Ben Blank Avatar answered Sep 23 '22 10:09

Ben Blank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!