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

遍历列表时删除另一列表元素触发IndexError的原因与解决

问题分析与解决

为什么会触发IndexError?

你猜的完全正确,tempList = myList并没有生成新列表,只是让tempList和myList指向同一个列表对象——相当于给同一个列表挂了两个名字。所以删除tempList里的元素时,myList的长度会同步缩短。

你的循环用了range(9),要遍历索引0到8,但删除元素后,myList的长度变成8,最大索引是7,当i=8时自然找不到对应元素,触发IndexError。

如何解除tempList与myList的关联?

要解除关联,你需要创建myList的独立副本,常用方法有这几种:

  • 切片法(最常用):tempList = myList[:]
  • 使用list构造函数:tempList = list(myList)
  • 列表推导式:tempList = [x for x in myList]
  • 借助copy模块:
    import copy
    tempList = copy.copy(myList)
    

修正后的代码示例

用切片法创建副本后,你可以安全地遍历原列表并修改副本:

myList = [1,2,3,4,5,6,7,8,9]
tempList = myList[:]  # 创建独立副本

# 遍历原列表元素,找到4就从tempList删除
for num in myList:
    if num == 4:
        tempList.remove(num)

print(tempList)  # 输出: [1, 2, 3, 5, 6, 7, 8, 9]

如果坚持用索引遍历,建议基于原列表的长度循环(原列表不会被修改):

myList = [1,2,3,4,5,6,7,8,9]
tempList = myList[:]

for i in range(len(myList)):
    if myList[i] == 4:
        del tempList[i]

print(tempList)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:15:37