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
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].