Python IndexError: meaning and fix

IndexError: You asked a list for a position it does not have.

Code that causes it

fruits = ["사과", "배"]
print(fruits[2])
Open in the runner

Positions start at 0. A list of 3 ends at position 2. The list is empty.

Check the length with len(). Use [-1] for the last item.

How to fix it

fruits = ["사과", "배"]
print(fruits[1])
Open in the runner

Why it happens

A list starts counting at 0. So a list with two items has only positions 0 and 1.

The official docs are in English. See it in the official Python docs

Back to the runnerMore errors