python runtime_error ai_generated true

IndexError: list index out of range

ID: python/indexerror-list-index-out-of-range

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2025-08-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active

Root Cause

Accessing an index in a list that does not exist, e.g., list of length 3 with index 5.

generic

中文

访问列表中不存在的索引,例如长度为 3 的列表使用索引 5。

Workarounds

  1. 95% success Check list length before access
    if len(my_list) > index: value = my_list[index]
  2. 90% success Use .get() equivalent for lists
    value = my_list[index] if index < len(my_list) else None

Dead Ends

Common approaches that don't work:

  1. Using try-except to ignore IndexError 70% fail

    Ignores the problem; test may pass incorrectly.

  2. Using negative indexing blindly 50% fail

    Negative indexing may access unintended elements if list length changes.