append、insert、extend都是python中列表用来添加元素的方法,但又有所区别。


  • append 默认添加一个对象到列表最后
1
2
3
4
5
6
7
8
9
In [4]: a = range(1,11)

In [5]: a
Out[5]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [6]: a.append('new')

In [7]: a
Out[7]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'new']
  • insert 可以在指定位置之前插入一个对象
1
2
3
4
5
6
7
8
9
10
11
12
In [17]: a = range(1,11)

In [18]: a
Out[18]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [19]: a.in
a.index a.insert

In [19]: a.insert(1,b)

In [20]: a
Out[20]: [1, ['a', 'b', 'c'], 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • extend 扩展列表,参数为可迭代对象,包括字符串,列表,元祖
1
2
3
4
5
6
7
8
9
10
11
12
In [29]: a
Out[29]: [1, 2, 3, 4, 5]

In [30]: b = range(6,11)

In [31]: b
Out[31]: [6, 7, 8, 9, 10]

In [32]: a.extend(b)

In [33]: a
Out[33]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]