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

Python初学者求助:为何触发IndexError: list assignment index out of range错误

解决Python列表索引赋值的IndexError问题

你的问题出在直接通过索引给空列表或无对应位置的列表赋值。Python里,空列表[]或者[]*5(这玩意儿还是空列表,因为空列表乘任何数都是空)根本没有x对应的索引位置,自然会抛IndexError。

给你几个可行的解决办法:

方法1:用append()添加元素

这是最直观也最常用的方式,直接把拼接好的名字追加到列表末尾:

player_first_name = ["Luka", "Nikola", "Giannis", "Stephen", "Jayson"]
player_last_name = ["Doncic", "Jokic", "Antetokounmpo", "Curry", "Tatum"]
player = []

for x in range(5):
    full_name = player_first_name[x] + " " + player_last_name[x]
    player.append(full_name)

方法2:预先初始化指定长度的列表

如果一定要用索引赋值,得先给列表每个索引位置预留空间,比如用[None] * 5创建一个长度为5、每个元素都是None的列表,之后就能通过索引赋值了:

player_first_name = ["Luka", "Nikola", "Giannis", "Stephen", "Jayson"]
player_last_name = ["Doncic", "Jokic", "Antetokounmpo", "Curry", "Tatum"]
player = [None] * 5  # 初始化长度为5的列表

for x in range(5):
    player[x] = player_first_name[x] + " " + player_last_name[x]

方法3:用列表推导式(更简洁)

一行搞定,Pythonic的写法:

player_first_name = ["Luka", "Nikola", "Giannis", "Stephen", "Jayson"]
player_last_name = ["Doncic", "Jokic", "Antetokounmpo", "Curry", "Tatum"]

player = [f"{first} {last}" for first, last in zip(player_first_name, player_last_name)]

这里用zip()把两个列表的元素一一配对,再用f-string拼接名字,比循环更简洁高效。

顺便提一句,你之前试的player = [] *5没用,因为空列表乘以任何整数结果还是空列表,只有非空列表乘以数才会重复元素扩展长度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:16:23