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

Python使用range函数向列表添加元素报IndexError索引越界问题

报错根因

出现IndexError: list assignment index out of range是两个逻辑问题叠加导致的:

  • 你初始化的numberinput是长度为0的空列表,本身没有任何可访问的索引位置。列表[索引] = 值的语法作用是修改列表中已有索引位置的元素,不能用来给空列表新增元素
  • 你用range(1, 11)生成的循环变量x取值是1到10,而Python列表的索引是从0开始计数的,就算你提前创建了长度为10的列表,最大合法索引是9,x取10的时候依然会触发索引越界。
正确写法

空列表动态加元素直接用内置的append()方法就行,不需要手动维护索引,这也是最常用的写法:

numberinput = []
for _ in range(10):
    arrayinput = input("Type the number you want to add to the array")
    # 如果需要存储数值类型而非输入返回的字符串,可以加一步类型转换:arrayinput = int(arrayinput)
    numberinput.append(arrayinput)
print(numberinput)

如果一定要用索引赋值的方式实现,需要先把列表初始化为对应长度,同时调整索引起始值匹配Python的从0计数规则:

# 提前创建长度为10的列表,用None做占位值
numberinput = [None] * 10
for x in range(10):
    arrayinput = input("Type the number you want to add to the array")
    numberinput[x] = arrayinput
print(numberinput)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 16:24:29