解决 Python 报错 IndexError: list assignment index out of range
分析 Python 对空列表直接按索引赋值抛出 IndexError 根因,提供 append、extend 与列表推导式安全写法方案。
问题现象
Traceback (most recent call last):
File "script.py", line 5, in <module>
my_list[0] = "val"
IndexError: list assignment index out of range
触发根因
空列表 my_list = [] 长度为 0,不能直接通过索引下标进行写入赋值。
解决步骤与操作命令
方案 A:使用 append() 动态追加元素
my_list = []
my_list.append("val")
方案 B:预先初始化固定长度列表
my_list = [None] * 10
my_list[0] = "val"
代码安全运行,越界异常消除。


