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

Python列表insert方法疑问:插入位置999后索引为何不是10?

Python列表insert插入后索引不符合预期的原因

你的代码如下:

ten = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = input('Position of the value you want to add ')
b = int(b)
a = input('Enter the value you want to add to list')
a = int(a)
ten.insert(b,a)

print(ten)

print('The lenght of this list is '+str(len(ten)))
sotim = input('Number you want to check')
sotim = int(sotim)
if sotim in ten:
    print('The number you ask is at position '+str(ten.index(sotim))+' in the list')
else:
    print('The number you ask is not in the list')

问题原因

当你输入b=999、a=18时,ten.index(18)返回9而非你预期的10,核心原因有两点:

  • Python列表索引从0开始计数:原列表ten包含9个元素,索引范围是0到8。插入元素后列表长度变为10,末尾元素的索引是9(0起始)。
  • insert函数的边界处理:当传入的插入位置pos大于当前列表长度时,insert会自动将元素插入到列表末尾,而非你指定的超大位置。这里原列表长度是9,999远大于9,所以18被插入到末尾,对应的索引就是9。

补充说明

  • 如果你习惯从1开始计数的位置显示,可以在输出时给索引加1,比如修改为:
    print('The number you ask is at position '+str(ten.index(sotim)+1)+' in the list')
    
  • 代码里存在拼写错误:lenght应改为length。

内容的提问来源于stack exchange,提问作者Gia Huy Ngô

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:39:57