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

Python自定义myMax函数运行报IndexError: list index out of range如何解决

报错原因
  • 代码没有做空输入校验,当调用myMax([])传入空列表时,maxx=L[0]尝试访问空列表的第0位元素,空列表不存在任何合法索引,因此触发IndexError: list index out of range越界错误。
  • 原代码中定义的f=len(L)变量没有被后续逻辑使用,属于冗余代码可直接删除。
修复方案

可根据业务需求选择以下两种处理方式:

方案1:空列表抛出友好提示(推荐,符合函数预期输入非空的逻辑)

def myMax(L):
    # 先做非空校验
    if not L:
        raise ValueError("输入列表不能为空,无法求取最大值")
    ind = 0
    maxx = L[0]
    for i in range(len(L)):
        if L[i] > maxx:
             maxx = L[i]
             ind = i
    return (ind, maxx)

print(myMax([1, 2, -9, 10])) # 输出 (3, 10)
# print(myMax([])) # 调用时会抛出明确的ValueError提示,而非模糊的索引越界

方案2:空列表返回约定默认值(适合需要兼容空输入的场景)

def myMax(L):
    if not L:
        # 空列表返回提前约定的默认值,可根据业务调整返回规则
        return (None, None)
    ind = 0
    maxx = L[0]
    for i in range(len(L)):
        if L[i] > maxx:
             maxx = L[i]
             ind = i
    return (ind, maxx)

print(myMax([1, 2, -9, 10])) # 输出 (3, 10)
print(myMax([])) # 输出 (None, None)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:36:01