IndexError: list index out of range even though its not

11
5
Traceback (most recent call last):
  File "/home/cg/root/6423329a7eaa5/main.py", line 2068, in <module>
charactercreate()
  File "/home/cg/root/6423329a7eaa5/main.py", line 2025, in charactercreate
getblade()  #creates character
  File "/home/cg/root/6423329a7eaa5/main.py", line 1996, in getblade
bossdefeated()   #gives the player starting dagger
  File "/home/cg/root/6423329a7eaa5/main.py", line 577, in bossdefeated
level2start()
  File "/home/cg/root/6423329a7eaa5/main.py", line 388, in level2start
fight2()
  File "/home/cg/root/6423329a7eaa5/main.py", line 35, in fight2
if(player[4] < monster[3]):
IndexError: list index out of range

i have the code set to print monster[3] and then player[4] right before the fight2 function is called just to make sure that the list index exists (11 and 5). they print just fine, they exist, but then when the code runs it says that they dont exist. makes no sense.
if anyone wants full code just ask although i must warn its quite messy

Not that I want to pull you apart, but if the code is quite messy, then it’s going to be difficult for you to debug, let alone someone else.

Try this (assuming that line 35 is still if(player[4] < monster[3]):)…
At line 34 introduce print(player, monster) so that you can see what’s there before you hit the if: branch – Python does not (in my experience) tell you that an index is out of range, if it’s not so.

Post back the output of said print() if you’re not too sure about the indexing.

1 Like

Did you consider the possibility, that the contents of the lists could change between the two times that you access player[4] or monster[3] (to print the values the first time, and to compare them the second time)? Or that the lists get reassigned?

We could, perhaps, start with the part from the beginning of fight2 (including the prints that you’re talking about), until the if(player[4] < monster[3]): line.

But aside from that, the names of functions in that error message deeply concern me. Just to make sure you understand: after the fight2 is done, you are expecting that the code will automatically go back to the point in level2start where fight2 was called, and continue the function where it left off - right? Similarly for all the other functions - when level2start finishes the code would go back to the point in bossdefeated where level2start was called, and so on. Calling a function is not like “going to” a specific point in the code. Instead, it is like asking for another calculation to be completed, so that the result can be used by the caller.