Llambri Thanasi
Llambri Thanasi

Reputation: 33

How to fix list index out of range?

I am having problems with this line. I am not really sure why it gives me list index out of range. I've tried couple of solutions so far none of them worked.

scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
# Print first 5
a = 0
for score in scoreboardSorted:
    print(str(score[0]) + ": " + str(score[1]) + " points")
    a = a + 1
    if a == 5:

This is the full section of this code

def endGame(points):
    scoreboard = []
    # Write score to scoreboard
    with open("scoreboard.csv", "a") as scoreboardFile:
        scoreboardWriter = csv.writer(scoreboardFile)
        scoreboardWriter.writerow([name, points])
    # Open scoreboard in read mode and store in memory
    scoreboardFile = open("scoreboard.csv", "rt")
    scoreboardReader = csv.reader(scoreboardFile)
    for i in scoreboardReader:
        scoreboard.append(i)
    print("\nGame over!")
    print("Well done " + str(name) + ", you got " + str(points) + " points.")
    print("\nTop 5:")
    # Sort list
    scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
    # Print first 5
    a = 0
    for score in scoreboardSorted:
        print(str(score[0]) + ": " + str(score[1]) + " points")
        a = a + 1
        if a == 5:
            break
    sys.exit()

The traceback is this

Traceback (most recent call last):
  File "E:\Nea\NEA-PROJECT.py", line 128, in <module>
    endGame(points)
  File "E:\Nea\NEA-PROJECT.py", line 30, in endGame
    scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
  File "E:\Nea\NEA-PROJECT.py", line 30, in <lambda>
    scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
IndexError: list index out of range

P.S: Please do not just post solutions and actually explain in detail. I am a student in secondary school who is still trying to learn and I would really appreciate it if u take your time and explain it. Thanks in advance.

Upvotes: 1

Views: 64

Answers (3)

Ofer Sadan
Ofer Sadan

Reputation: 11982

t[1] in your lambda function is impossible if t (an item in scoreboard) has less than 2 values (1 or 0). This probably means you have too few values in your csv file.

Either you fix the values in your csv or you fallback on some default value when sorting:

scoreboardSorted = sorted(scoreboard, key = lambda t: t[1] if len(t) > 1 else 0, reverse = True)

Note that I used 0 as the default here but if that gives you the wrong sorted order or a type error you'll have to figure out another suitable value as the default.

Upvotes: 2

John Gordon
John Gordon

Reputation: 33359

sorted(scoreboard, key=lambda t: t[1], reverse=True)

This assumes that each item in scoreboards is itself a sequence of at least two items.

It sounds like there is least one item in scoreboards that has fewer than two items.

Upvotes: 0

Alexander
Alexander

Reputation: 109746

Your scoreboard is missing data. For example, the second row in the table below is missing its second value.

a = [[1, 2], [3,], [5, 6]]
>>> sorted(a, key=lambda t: t[1])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-341-fea6d7792ad0> in <module>
      1 a = [[1, 2], [3,], [5, 6]]
----> 2 sorted(a, key=lambda t: t[1])

<ipython-input-341-fea6d7792ad0> in <lambda>(t)
      1 a = [[1, 2], [3,], [5, 6]]
----> 2 sorted(a, key=lambda t: t[1])

IndexError: list index out of range

You could use a ternary to give missing values a default, e.g. zero.

>>> sorted(a, key=lambda t: t[1] if len(t) > 1 else 0)
[[3], [1, 2], [5, 6]]

Upvotes: 2

Related Questions