如何使用 list.insert 将 Python 中的元素添加到列表的末尾?

How to add element in Python to the end of list using list.insert?

有一个列表,例如

a=[1,2,3,4]

我可以用

a.append(some_value)

在列表末尾添加元素,

a.insert(exact_position, some_value)

在列表中的任何其他位置插入元素 但不在末尾 as

a.insert(-1, 5)

将 return [1,2,3,5,4]。 那么如何使用 list.insert(position, value)?

将元素添加到列表的末尾

在这种情况下,您必须使用 len 将新的序号位置传递给 insert

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

list.insert 与任何索引 >= len(of_the_list) 将值放在列表的末尾。它的行为类似于 append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

时间复杂度,追加O(1),插入O(n)