Python如何判断列表指定索引是否存在以避免IndexError越界错误
错误原因
Python 列表的索引从0开始计数,长度为n的列表合法索引范围是0 ~ n-1。你当前的common_list长度为3,合法最大索引是2,直接在if判断条件中访问common_list[3]时,访问动作本身就会触发IndexError,不会执行后续的判断逻辑。
正确实现方案
根据你的实际需求可以选择以下两种写法:
方案1:目标索引不存在时直接插入(超界则追加到末尾)
list.insert(i, x)方法本身支持传入大于等于列表长度的索引,此时元素会直接追加到列表末尾,符合你当前的场景需求:
common_list = ['Potato', 'Tomato', 'Carrot'] target_index = 3 # 先通过长度判断索引是否合法,避免直接访问越界索引 if len(common_list) <= target_index: common_list.insert(target_index, 'Lemon')
运行后common_list结果为['Potato', 'Tomato', 'Carrot', 'Lemon']。
方案2:保证插入元素一定在目标索引位置(补全中间空位)
如果你需要插入后元素严格位于target_index,中间空缺的索引位置用占位值(比如None)补全,可以用以下写法:
common_list = ['Potato', 'Tomato', 'Carrot'] target_index = 3 insert_value = 'Lemon' if len(common_list) <= target_index: # 补全中间空缺的索引位置 common_list += [None] * (target_index - len(common_list) + 1) common_list[target_index] = insert_value
如果原列表长度为1、目标索引为3,运行后列表结果为['Potato', None, None, 'Lemon'],保证插入值在指定索引位。
扩展:索引存在时判断值是否为空再替换
如果你的需求包含「索引存在时,如果对应位置值为空也替换为目标值」,可以补充判断逻辑:
target_index = 3 insert_value = 'Lemon' if len(common_list) > target_index: # 索引合法时再判断值是否为空 if not common_list[target_index]: common_list[target_index] = insert_value else: common_list.insert(target_index, insert_value)
内容的提问来源于stack exchange,提问作者Dariiu
相关产品推荐
相关产品推荐

