Skip to content
Advertisement

How do I fix a ‘ list index out of range’ error?

I’m a beginner programmer currently learning Python and I’m programming a game for the first time.

The name and result of the winner is written to an external file and can be read from and displayed in the form of a table.

However, I am getting an error here:

sort = sorted(results, key = itemgetter(0), reverse = True)
IndexError: list index out of range

This is the whole function for reference:

def leadTable():    
  results = []
  with open('winnerScores.txt', 'r') as file:
      r = csv.reader(file, delimiter = ',')
      for row in r:
          results.append(row)
      sort = sorted(results, key = itemgetter(0), reverse = True)
      print(" nnn==================== Leaderboard Table ====================")
      print(" Scoret  Namet")
      print("____________________________________________________________n")
      for row in sort:
          print ("|",row[0]," t " ,row[1]," "*(9-len(row[1]))," ","|")
  print("____________________________________________________________nnn")

How could I fix this?

Advertisement

Answer

Your file has empty lines, which csv.reader is returning as empty lists. You should skip them when filling in `results.

for row in r:
    if len(row) >= 2:
        results.append(row)

I used >= 2 because the code that prints the leaderboard requires row[0] and row[1] to be filled in.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement