0

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)

1
  • res = [[0 for i in range(COLS)] for i in range(ROWS)] ? Commented Apr 26, 2022 at 20:11

2 Answers 2

2

Swap the ROWS and COLS like so:

res = [[0 for i in range(COLS)] for i in range(ROWS)]
Sign up to request clarification or add additional context in comments.

Comments

1

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.