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
6 Answers 6
You get the IndexError because you can't assign to an index in the list beyond the current length of the list. Since grid2 is initialized to an empty list, any attempt to index it will raise this error.
One correct way to write your nested list comprehension using for loops would be to construct the inner list first for each row, then append this to grid2:
grid2 = []
for i in range(rows):
inner = []
for j in range(cols):
inner.append(0)
grid2.append(inner)
Comments
you should initialize grid2=np.empty([rows, cols]) instead please refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html#numpy.empty for more details
2 Comments
numpy, why not np.zeros? This seems more aligned with what OP wants to do.In the first case each cell exists, so you can access them by index, but in the second case they do not still exist, the other way is
grid2 = []
for i in range(rows):
tmp = []
for j in range(cols):
tmp.append(0)
grid2.append(tmp)
And in fact if you reduce this code once you have the following, and reducing again with another list comprehension you have your first code
grid2 = []
for i in range(rows):
grid2.append([0 for j in range(cols)])
Comments
you are trying to access the second "dimension" or an inner loop without creating here, you may use:
rows = 5
cols = 5
grid2 = []
for _ in range(rows):
grid2.append([])
for _ in range(cols):
grid2[-1].append(0)
print(grid2)
or you may use:
grid2 = []
for _ in range(rows):
grid2.append([0] * cols)
Comments
Try this:
rows = 5
cols = 5
arr = [[0 for x in range(cols)] for x in range(rows)]
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]]
Comments
You need to use .append() fucntion to add elements to list.
grid2 = []
for i in range(rows):
grid2.append([])
for j in range(cols):
grid2[i].append(0)
print(grid2)
more efficiently:
grid2 = [[0]*cols] * rows
1 Comment
grid2 = [[0]*2] * 3 ; grid2[2][1]=3 -> [[0, 3], [0, 3], [0, 3]]Explore related questions
See similar questions with these tags.
append.