Python List insert()方法详解

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

2.语法
list.insert(index, obj)

3.参数
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; -2 表示从倒数第1位插入obj
场景4:当index < 0 且 abs(index) >= len(list)时,从头部插入obj
场景5:当index >= len(list)时,从尾部插入obj

4.返回值
该方法没有返回值,但会在列表指定位置插入对象。

5.实例

>>> lst = [1,2,3,4,5] #创建一个列表
>>> lst.insert(0,0) #从列表第1个位置,插入元素0 --场景1 
>>> lst
[0, 1, 2, 3, 4, 5]
>>> lst.insert(6,7) #从列表第6个位置,插入元素7 --场景2 
>>> lst
[0, 1, 2, 3, 4, 5, 7]
>>> lst.insert(-1,6) #从列表第-1个位置,插入元素6 --场景3 
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7]

>>> lst.insert(-20,10) #从列表第-20个位置,插入元素10 --场景4 
>>> lst
[10, 0, 1, 2, 3, 4, 5, 6, 7]

>>> lst.insert(30,20) #从列表第30个位置,插入元素20 --场景5 
>>> lst
[10, 0, 1, 2, 3, 4, 5, 6, 7, 20]

 

posted @ 2017-11-20 00:03  碧水幽幽泉  阅读(24578)  评论(0编辑  收藏  举报