Home > other >  IndexError: list index out of range in a loop
IndexError: list index out of range in a loop

Time:07-13

I have a 3D array. I want extract the 3rd element. For example, here I want to print 6, 9, 20. But Python is throwing this error.

values = [
    [[0, 6], [0, 9], [0, 20]],
    [[1, 2], [1, 4], [1, 9 ]]]
i=0
for j in range(0,len(values[i])):
   print(values[i][i][j])

Not sure where this is going wrong because print(values[0][0][1]) works fine and gives 6 as it should

CodePudding user response:

in here len(values[i]) is 3 hence the range(0, len(values[i]) gives you values 0,1,2 and the length of [0,6] is 2 and you cant access element with index 2

hence it gives you index out of range error

CodePudding user response:

The value of j in for j in range(0,len(values[i])) become 0,1,2 but when value of j is 2 and run values[i][i][j] and i=0 the code run values[0][0][2] and this is out of range value for [0,6]

to print 6, 9, 20. can use this block of code:

values = [[[0, 6], [0, 9],[ 0, 20]], [[1, 2], [1, 4], [1, 9]]]
for j in range(len(values[0])):
    print(values[0][j][1])
  • Related