Skip to content

Instantly share code, notes, and snippets.

@tcpdump-examples
Created February 8, 2022 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcpdump-examples/d4938481859f9cf8715240bc8a2a0be7 to your computer and use it in GitHub Desktop.
Save tcpdump-examples/d4938481859f9cf8715240bc8a2a0be7 to your computer and use it in GitHub Desktop.

insert()往列表的指定位置添加元素,举个例子:

insert的列子

1 a = ["hello", "world", "dlrb"] 2 a.insert(1, "girl") 3 print(a) 输出结果:

['hello', 'girl', 'world', 'dlrb'] 我们在列表a的位置1插入元素girl

A = [1,2,3,4,5,6,8] A.insert( 6, 7) print(A)

result: [1,2,3,4,5,6,7,8]

insert共有如下5种场景:

  • 1:index=0时,从头部插入obj。
  • 2:index > 0 且 index < len(list)时,在index的位置插入obj。
  • 3:当index < 0 且 abs(index) < len(list)时,从中间插入obj,如:-1 表示从倒数第1位插入obj。
  • 4:当index < 0 且 abs(index) >= len(list)时,从头部插入obj。
  • 5:当index >= len(list)时,从尾部插入obj。

append 与insert的区别

两者都是对python内的列表进行操作,append()方法是值在列表的末尾增加一个数据项,insert()方法是指在某个特定位置前加一个数据项。

Python内的list实现是通过数组实现的,而不是链表的形式,所以每当执行insert()操作时,都要将插入位置的元素向后移动才能在相应的位置插入元素,执行append()操作时,如果分配的空间还足够大的话那么就可以直接插到最后,如果空间不够的话就需要将已有的数据复制到一片更大的空间后再插入新元素,insert()空间不够的话也是同样。

参考: python list insert

append list in python

python 3 list methods examples

sort list in python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment