Home > Blockchain >  Can't figure out why I am getting list index out of range
Can't figure out why I am getting list index out of range

Time:03-14

When I run my function, I am getting list index out of range for the underlined part of my function. When I change it to p-1 however it does not give me the error anymore except all my numbers are now negative and its not what I want. Any help would be greatly appreciated.

Code:

def smallest_increase(pop_stats):
    
    smallest_year = 0
    
    smallest_increase = 0
    
    for p in range (len(pop_stats)):
        
        increases = pop_stats[p - 1][1] pop_stats[p][1] 
        
        if pop_stats[p 0][1]-pop_stats[p][1]<increases and pop_stats[p][1]-pop_stats[p][1]>=0:
            
            increases = pop_stats[p 1(this is one that give error)][1]   pop_stats[p][1]
            
             
            
            print (increases)
def smallest_increase(pop_stats):
    
    smallest_year = 0
    
    smallest_increase = 0
    
    for p in range (len(pop_stats)):
        
        increases = pop_stats[p - 1][1] pop_stats[p][1] 
        
        if pop_stats[p 0][1]-pop_stats[p][1]<increases and pop_stats[p][1]-pop_stats[p][1]>=0:
            
            increases = pop_stats[p 1][1]   pop_stats[p][1]
            
             
            
            print (increases)

Image with marked line

CodePudding user response:

for p in range (len(pop_stats)): will repeat the loop for each index of pop_stats. The last value of p will be the index for the end of pop_stats. This means that [p 1] tries to access an element off the end of the list.

Your if statement looks weird as well.

pop_stats[p 0][1]-pop_stats[p][1] will always be 0. pop_stats[p][1]-pop_stats[p][1] will always be 0.

CodePudding user response:

It would be helpful to know how you're using the function and what list you're giving it that raises the error. But I would suggest checking p 1 < len(pop_stats) before attempting to access pop_stats[p 1].

CodePudding user response:

You iterate p over range(len(pop_stats)). len(pop_stats) is the number of elements in that list, and the range over that number goes from zero to the number of elements in the list, but not including that number (remember that range is not including the upper bound of the range). So if, for instance, pop_stats has 100 elements in it, you get the range from zero to 99 inclusive. But since indexing starts with zero, the first element in the list will be pop_stats[0], and the last element (the hundredth) will be pop_stats[99]. With p 1 you get pop_stats[100], which is one more than the maximum index in your list.

  • Related