Home > OS >  Error in Creating a 2d array via plain for loop iteration but not if created via list comprehension
Error in Creating a 2d array via plain for loop iteration but not if created via list comprehension

Time:11-26

I am trying to create a 2d array by the following two methods. Now I get the 2d array when I use the list comprehension but I receive and error of Index out of bound when I use the normal for loop. Can someone please explain me as to why did this happen?

r=3
c=4
new = []
temp =[]
for i in range(r):
    for j in range(c):
        new[i][j]=0
        
print(new)

Result - IndexError: list index out of range

temp = [[0 for _ in range(c)] for _ in range(r)]
print("Temp", temp)

Result - [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

CodePudding user response:

You're trying to access values from an empty list, use append with an auxiliary list as follow:

>>> for i in range(r):
...     aux = []
...     for j in range(c):
...             aux.append(0)
...     new.append(aux)

CodePudding user response:

In the second approach

temp = [[0 for _ in range(c)] for _ in range(r)]

you set each element of the new temp list to another list and fill it in.

When you do this in the first approach:

new[i][j]=0

you have two problems, first new[i] is beyond the range of the zero sized list. This blows up. If it didn't give an error, you are then trying to index into a thing that doesn't exist. Even if you could make it an empty list by default, the index j would also be out of range.

  • Related