0

While running this code:

N=7
F=2
ar=[]
for i in range(N):
    for j in range(F+1):
        ar[i][j]=1
print(ar)     

it's showing the error below and I don't understand why.

IndexError Traceback (most recent call last) in 4 for i in range(N): 5 for j in range(F+1): ----> 6 ar[i][j]=1 7 print(ar)

IndexError: list index out of range

The important thing I understood is: While initializing an array(in any dimension) We should give a default value to all the positons of array. Then only initialization completes. After that we can change or recieve new values to any positon of the array. The below code worked for me perfectly

N=7
F=2

#INITIALIZATION of 7 x 2 array with deafult value as 0
ar=[[0]*F for x in range(N)]

#RECEIVING NEW VALUES TO THE INITIALIZED ARRAY
for i in range(N):
    for j in range(F):
        ar[i][j]=int(input())
print(ar)
  • you array `ar` is empty... so you can not access `ar[0]` or any other element. you need to initialize your array. you coud use `ar = [[1]*F for _ in range(N)]`. – hiro protagonist Aug 30 '19 at 06:36
  • Because your array ios empty and it doesn't exist the index i or j. You should use **append** or **insert** to insert elements in array – nacho Aug 30 '19 at 06:37
  • The above comments are correct. Also, why `F+1`? – Selcuk Aug 30 '19 at 06:38
  • Thank you all, I understood it perfectly now. ie First we need to initialize by giving a default value for all positions in array. Then only initialization completes. After that we can change or recieve new values to our array locations right? My below code worked perfectly N=7 F=2 ar=[[0]*F for x in range(N)] for i in range(N): for j in range(F): ar[i][j]=int(input()) print(ar) – Fairoos Ok Aug 30 '19 at 15:12

1 Answers1

-1

You are trying to access i-th element of empty array. For example you will get the same error in:

arr = []
arr[0]

You need to initialize the array first. Try googling initialize 2d array in python or something similar, or just look on SO: How to initialize a two-dimensional array in Python?

Drecker
  • 1,215
  • 10
  • 24
  • 1
    If this is a duplicate, please flag it as such instead of posting duplicate answers. – Selcuk Aug 30 '19 at 06:38
  • 1
    @Selcuk it does not feel like duplicate to me, I feel like this question is stuck at fundamentals of python, while the linked one asks just more specific questions (i.e. you can NOT answer the liked question by "you are accessing element of empty array" while you CAN answer this question in that way). if you feel like it is duplicate, flag it as such – Drecker Aug 30 '19 at 06:41