I am trying to generate an empty 2-dimensional array by using to for-loops. I have found one method that works, and it looks like this:
rows = 5
cols = 5
grid1 = []
grid1 = [[0 for i in range(cols)] for j in range(rows)]
print(grid1)
Output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
However, when I try to write the for loops in "normal" syntax it throws an error. Why can't I write it in normal syntax?
rows = 5
cols = 5
grid2 = []
for i in range(rows):
for j in range(cols):
grid2[i][j] = 0
print(grid2)
Output:
Exception has occurred: IndexError
list index out of range
File "C:\Users\Bruker\Downloads\test.py", line 8, in <module>
grid2[i][j] = 0
append.