Collect from Template was collected from
Modified by zmrenwu's blog

Python List: difference between insert, append, and extend

insert: It takes two arguments, and insert the one element into the desired position. Note: index -1 will insert into last two position of the list, if you want to insert to end of list, please use len().

>>> a = [1,2,3]
>>> a.insert(0,4)
>>> a
[4, 1, 2, 3]
>>> a.insert(-1,5)
>>> a
[4, 1, 2, 5, 3]
>>> a.insert(len(a),6)
>>> a
[4, 1, 2, 5, 3, 6]

Append: it can append one element or multiple elemenets.

>>> a = ['a','b','c']
>>> b, c = ['d'], ['e','f']
>>> a.append(b)
>>> a
['a', 'b', 'c', ['d']]
>>> a.append(c)
>>> a
['a', 'b', 'c', ['d'], ['e', 'f']]

extend: it extends current list without addint sub list

>>> a = ['a','b','c']
>>> b, c = ['d'], ['e','f']
>>> a.extend(b)
>>> a
['a', 'b', 'c', 'd']
>>> a.extend(c)
>>> a
['a', 'b', 'c', 'd', 'e', 'f']

发表评论

    暂无评论