Python list根据下标插入/删除元素

在指定位置插入几个数字
l=[1,2,3,4,5,6]
l[0:0]=[11,22,33,44,55]
print(l)

[11, 22, 33, 44, 55, 1, 2, 3, 4, 5, 6]

 

python list的remove方法,接受的参数是元素的值, 如果要想根据下标来移除元素,有两种方法:

方法一: 使用del(这种方法的好处是能用切片,如del l[-1:-3:-1])

a = [1,2,3,4] del a[-1]

方法二: 使用pop方法来移除指定下标的元素

a = [1,2,3,4] a.pop()

pop()方法也可以不指定参数,不指定参数会移除最后一个元素。

 

转载自:http://www.voidcn.com/code/p-hirfbddj-g.html

posted @ 2021-04-01 11:43  larybird  阅读(3576)  评论(0编辑  收藏  举报