You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python出现IndexError: list index out of range错误,求排查帮助

Fixing Your IndexError: List Index Out of Range

Hey there! Let's break down why you're hitting that IndexError: list index out of range error and fix it up.

The Root Cause

Take a look at your first for loop:

for x in range(0,9):
    print("Enter user: ",x)
    y = []
    y.append(input())

Every single time this loop runs, you're creating a brand new empty list with y = []. That means after each iteration, the previous version of y gets tossed out, and by the end of the loop, y only holds the very last input you typed (so its length is just 1).

Then your second loop tries to access y[0] through y[8]:

for z in range(0,9):
    print(y[z])

Since y only has 1 element, trying to access indexes 1 and beyond immediately triggers the index out of range error.

The Simple Fix

Move the y = [] line outside the first loop. This way, you're adding all your inputs to the same list instead of creating a new one each time:

y = []  # Initialize the list once before the loop starts
for x in range(0,9):
    print("Enter user: ",x)
    y.append(input())
for z in range(0,9):
    print(y[z])

Now, every input gets appended to the same y list. After the first loop finishes, y will have 9 elements, and your second loop can safely access each index from 0 to 8 without any issues.

内容的提问来源于stack exchange,提问作者Nahu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:17:52