Skip to content

IndexError: list index out of range

Error message

                list index out of range
              

Quick summary

You tried to access a list element at an index that is beyond the list's valid range (0 to `len(list) - 1`).

Why this happens

  • Index is greater than or equal to the list length

  • The list is empty but was accessed at index 0

  • Off-by-one error in a loop boundary (e.g., range(len(lst) + 1))

Minimal example

✗ Broken code
nums = [1, 2, 3]
print(nums[5])
✓ Fixed code
nums = [1, 2, 3]
print(nums[2])

nums[5] is out of range — the list has 3 elements (indices 0–2). Use a valid index like nums[2] to access the last element.

How to diagnose

  • Print len(lst) and the index being accessed

  • Check loop bounds — does the index stay within 0 to len(lst) - 1?

  • Verify the list is not empty before accessing elements

How to fix

  • Check if index < len(lst) before accessing the element

  • Fix the loop boundary (use range(len(lst)), not range(len(lst) + 1))

  • Use try/except IndexError to handle the error gracefully

How to prevent

  • Prefer for item in lst over for i in range(len(lst)) when possible

  • Check the list length before accessing by index

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language