Alex
Alex

Reputation: 1537

Matrix (list) in python

I want to create a matrix ROW x COLS based on another matrix original size ROW x COLS.

ROWS = len(mat)
COLS = len(mat[0])
    
res = [[0 for i in range(ROWS)] for i in range(COLS)]

The above code doesn't work for the following edge case:

mat = [[3],[4],[5],[5],[3]]

My desired output is:

[[0],[0],[0],[0],[0]]

However, what I get is:

[[0,0,0,0,0]]

How can I adapt my code to work with any case? ( I do not want to use numpy or any other libraries)

Upvotes: 0

Views: 67

Answers (2)

Stanley
Stanley

Reputation: 320

Swap the ROWS and COLS like so:

res = [[0 for i in range(COLS)] for i in range(ROWS)]

Upvotes: 2

not_speshal
not_speshal

Reputation: 23146

Try:

>>> [[0 for i in range(len(mat[0]))] for j in range(len(mat))]
[[0], [0], [0], [0], [0]]

Also better to use different loop variables instead of i for both:

Upvotes: 1

Related Questions