Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Syntax Error:Creating An 2d List Filled With Zero

How Could I Initialize An 2D List Filled With Zeroes Without Any Additional Library/Module

here what is my attempt

table = [0 for i in range(amount + 1)[0 for j in range(len(coins))]]

it works in case of 1d list:Vector But Fails In Case Of 2d

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code:
table = [0 for i in range(amount + 1)]
O/P:
[0,0,0,0,0,0,0,0,0,0,0,0]

Code:
table = [0 for i in range(amount + 1)[0 for j in range(len(coins))]]
O/P:
Syntax Error

>Solution :

You are putting the inner comprehension part in the wrong position. Try:

rows, cols = 4, 5
table = [[0 for _ in range(cols)] for _ in range(rows)]
print(table)
# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

First, _ here is nothing strange; it is just a dummy name, which we don’t care. We could name it i for example, and nothing changes.

[... for _ in range(rows)] makes a list with length rows, with the items given by .... Now ... was [0 for _ in range(cols)], i.e., a list of zeros with length cols. Therefore, the result is a list (having length row) of [0, 0, ..., 0].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading