Home > Enterprise >  Python error - "List index out of range" on my code
Python error - "List index out of range" on my code

Time:11-11

when I run this code below I am getting IndexError: list index out of range.

I am trying to go through the list "years" and compare the value found in the list to the list of lists "data". I am unsure why I am getting the error below. Any thoughts on why this is the case?

PS. I am new to writing code... so pls excuse my ignorance lol..

attempts_per_year = []
n = 0
y = 0
count = 0

for element in years: 
    if y <= len(data) and years[n] == data[y][0]:
        count  = 1
        y  = 1
                             
    elif years[n] != data[y][0]:
        y  = 1
        
    else:
        attempts_per_year.append (years[n], count)
        count = 0
        n  = 1
IndexError                                Traceback (most recent call last)
<ipython-input-145-07e49ab31e13> in <module>
      5 
      6 for element in years:
----> 7     if y <= len(data) and years[n] == data[y][0]:
      8             count  = 1
      9             y  = 1

IndexError: list index out of range

CodePudding user response:

Python indexes lists from 0 and your <= len(data) allows it to go past the end of the list. Should be < len(data). data will range from 0 to len(data) - 1.

CodePudding user response:

That means you don't have n elements in the "years" array, or you don't have y elements in the "data" two dimensional array, or the data[y] array is empty. You will get that same error with this code

# initialize years array with 3 elements
years = [2020, 2021, 2022]
if years[0] > 0:
    # this is ok
    print("years[0] == "   str(years[0]))
# Next line gets "IndexError: list index out of range"
if years[3] == 0:
    # years only has 3 elements,
    # Can only reference years[0], years[1] and years[2]
    program_never_reaches_here = 1 

CodePudding user response:

----> 7 if y <= len(data) and years[n] == data[y][0]: This line of code is actually causing the error because your index starts from 0 and should be 1 less than the actual length of the data, so y < len (data) might fix your issue.

CodePudding user response:

Thank you all for your feedbacks! I got it to work! :)

  • Related