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

Python代码执行偶发IndexError: list index out of range错误的原因是什么?

为什么这段代码会抛出IndexError: list index out of range?

咱们来拆解下你遇到的问题:

你的代码里用了random.randint(0, len(list1)),这里的关键是**randint(a, b)会返回一个介于a和b之间的整数,而且是包含a和b两个端点的**。

看你的list1,它的长度是5,对应的有效索引是0、1、2、3、4(因为Python列表是从0开始计数的)。但len(list1)返回的是5,所以randint(0,5)可能会生成0到5之间的任意整数——包括5。

当随机数抽到5的时候,你去访问list1[5]或者list2[5],自然就会触发IndexError,因为这两个列表根本没有索引为5的元素。

怎么修复?

很简单,有两种常用的解决思路:

  • 把randint的上限改成len(list1)-1,确保生成的索引在有效范围内
  • 用random.randrange(len(list1)),它的上限是不包含的,默认从0开始,刚好匹配列表的索引范围

举个修复后的例子:

import random
list1 = ['afgdddd', 'bcbvnbn', 'casretb', 'dbcbv ', 'egfhsgs']
list2 = ['a5y5546', 'brtewtwret', 'chrtyey', 'dqawtet', 'egreg']
choice1 = random.randint(0, len(list1)-1)  # 限制上限为有效最大索引
print(list1[choice1])
print(list2[choice1])

或者用更简洁的randrange写法:

choice1 = random.randrange(len(list1))

这样就不会再出现索引越界的问题啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:06:46