3

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
1
  • 2
    You can't assign to an index in the list beyond the current length of the list. The equivalent way to write the list comprehension would be to use append. Commented Apr 3, 2020 at 8:37

6 Answers 6

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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

If using numpy, why not np.zeros? This seems more aligned with what OP wants to do.
since you want to fill your array with zeros then it makes more sense to initialize it with zeros (np.zeros), otherwise empty declaration is faster if you later want to fill it with non zeros values
0

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

0

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

0

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

-1

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

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.