1 Fork me on GitHub

Python常用数据结构-列表 ——2.3 列表的方法 insert()

2.3列表的方法  insert()

insert(index,item):将一个对象插入到指定索引位置
入参:索引值index,一个对象item
返回:None
原索引位置及后面的元素后移一位

例1:

li = [0,1,2]
print("插入前:",li)    #  打印[0,1,2]

#  在索引0的位置插入元素
li.insert(0,"hogwarts")
print("插入后:",li)    #  打印["hogwarts",0,1,2]

打印后:

 

 

例2:

li13 = [1,2,3,4,5]
li13.insert(0,"hello")    #  在索引为0的位置插入hello
print(li13)
li13.insert(3,"python")   #  在索引为3的位置插入python
print(li13)

打印后:

 

 
注意:插入后原索引位置和元素位置后移一位



posted @ 2022-04-25 18:03  v_jjling  阅读(311)  评论(0编辑  收藏  举报
AmazingCounters.com