python: insert()函数用法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/TeFuirnever/article/details/89282694

python insert()函数用于将指定对象插入列表的指定位置。

list.insert(index, obj)

   
   
  • 1

参数:

  • index:对象obj需要插入的索引位置。

  • obj:要插入列表中的对象。

共有如下5种场景:

  • 1:index=0时,从头部插入obj。

  • 2:index > 0 且 index < len(list)时,在index的位置插入obj。

  • 3:当index < 0 且 abs(index) < len(list)时,从中间插入obj,如:-1 表示从倒数第1位插入obj。

  • 4:当index < 0 且 abs(index) >= len(list)时,从头部插入obj。

  • 5:当index >= len(list)时,从尾部插入obj。

list.insert(index = -1, obj)除外,当index = -1时,是插在倒数第二位的,也就是:

lst = [2,2,2,2,2,2]
lst.insert(-1,6)
print(lst)

   
   
  • 1
  • 2
  • 3
> [2, 2, 2, 2, 2, 6, 2]

   
   
  • 1
例子1:
lst = [2,2,2,2,2,2]
lst.insert(0,0)# index=0时,从头部插入obj
print(lst)

   
   
  • 1
  • 2
  • 3
> [0, 2, 2, 2, 2, 2, 2]

   
   
  • 1
例子2:
lst = [2,2,2,2,2,2]
lst.insert(6,7)# index > 0 且 index < len(list)时,在index的位置插入obj
print(lst)

   
   
  • 1
  • 2
  • 3
> [2, 2, 2, 2, 2, 2, 7]

   
   
  • 1
例子3:
lst = [2,2,2,2,2,2]
lst.insert(-2,6)# 当index < 0 且 abs(index) < len(list)时,从中间插入obj
print(lst)

   
   
  • 1
  • 2
  • 3
> [2, 2, 2, 2, 6, 2, 2]

   
   
  • 1
例子4:
lst = [2,2,2,2,2,2]
lst.insert(-20,10)# 当index < 0 且 abs(index) >= len(list)时,从头部插入obj
print(lst)

   
   
  • 1
  • 2
  • 3
> [10, 2, 2, 2, 2, 2, 2]

   
   
  • 1
例子5:
lst = [2,2,2,2,2,2]
lst.insert(30,20)# 当index >= len(list)时,从尾部插入obj
print(lst)

   
   
  • 1
  • 2
  • 3
> [2, 2, 2, 2, 2, 2, 20]

   
   
  • 1
                                </div>
            <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e9f16cbbc2.css" rel="stylesheet">
                </div>
  • 87
    点赞
  • 321
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值