Search code examples
pythonlistindexingindex-error

IndexError: list index out of range longitude


Looking to make a function that will read a file of animal names with latitude and longitude, it will then return the #animals within a set area, i however keep getting an Index error and i'm not sure why, im still new to Python and just need a bit of help :')

def LocationCount(FileName, Distance, Lat2, Lon2):     
    List =[]                                                    
    File = open(FileName, "r")                                  
    for line in File:                                          
            List.append(LineToList(line))                       
    File.close()                                                

    List2 =[]
    ListCount = 0
    while ListCount <= len(List):
        if CalculateDistance(List[ListCount][1], List[ListCount][2], Lat2, Lon2) <= Distance:
            List2.append(line)
        ListCount += 1
    return(List2)

S = LocationCount("Mammal.txt", 10, 54.988056, -1.619444) 
print (len(List2))

Solution

  • while ListCount <= len(List):

    Change it to be,

    while ListCount < len(List): Lists are 0 indexed.

    Also you are storing the value in S and trying to print list2, which is undefined at this scope.

    S = LocationCount("Mammal.txt", 10, 54.988056, -1.619444) print (len(List2))

    replace it to be,

    S = LocationCount("Mammal.txt", 10, 54.988056, -1.619444) print len(S)