为什么a.insert(-1,x)不能模仿a.append(x)?

时间:2017-07-24 20:10:07

标签: python list insert append

所以我有以下Python代码,它将数字1-10附加到列表values

values = []

for value in range(1, 11):
    values.append(value)

print(values)

正如预期的那样,给我们[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

虽然不切实际,但出于好奇,我尝试使用insert()代替append()重新创建此结果:

values = []

for value in range(1, 11):
    values.insert(-1, value)

print(values)

这给了我结果[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

我也尝试过其他范围,并且每次都会发生同样的事情:它是按升序排列的,除了最小数字在最后。

Python Documentation Tutorial开始,我现在知道a.insert(len(a), x)可以用来模仿a.append(x)。但是,我仍然不明白为什么将值插入列表中的最后一个位置除了最小值之外。

4 个答案:

答案 0 :(得分:2)

要理解的基本要点是-1len(a)不同。它确实与len(a) - 1

相同
In [396]: x = [1, 2, 3]

In [397]: x[-1]
Out[397]: 3

In [398]: x[len(x) - 1]
Out[398]: 3 

当列表的大小为1或更大时,len(a) - 1将始终指向最后一个元素之前的位置(或者,技术上,指向最后一个元素当前所在的位置),这是{ {1}}会放置您的新项目。

list.insert

正如您已经发现的那样,In [400]: x.insert(-1, 4); x Out[400]: [1, 2, 4, 3] 指向最后一个元素之后的位置,即len(a)插入元素的位置。因此,list.append-1将指向最后一个元素的位置,len(a) - 1将最后一个元素推向右侧,并将新元素放在最后一个元素中#39旧位置。

答案 1 :(得分:2)

我认为这是因为insert在指定位置之前将放入元素中。那么a.insert(-1, value)所做的是,它将value放在最后一个元素之前,因此成为倒数第二个元素。但是当列表为空时,没有这样的倒数第二个元素,它将它放在最后一个索引中。

>>> a=[]
>>> a.insert(-1, 1)
>>> a
[1] #list is empty so it is inserted in the last index
>>> a.insert(-1, 2)
>>> a
[2, 1] #It placed the 2 on the second to last position, right before the 1

答案 2 :(得分:1)

当您插入第一个项目(数字1)时,它会插入到列表的确切末尾,因为列表中没有任何其他项目。一旦发生这种情况,其余的插入就会发生在列表的最后一项之前,因为-1是列表的最后一项,insert()在指定的索引之前插入。

我真的很惊讶insert()在空列表中工作。

答案 3 :(得分:1)

这是因为-1len(value)-1或列表中最后一项的索引相匹配,因此如果您打开list.insert()来电,请value列表更改为:

[]  # insert(-1, 1) -> -1 translates to -1 (unclear state)
[1]  # insert(-1, 2) -> -1 translates to 0
[2, 1]  # insert(-1, 3) -> -1 translates to 1
[2, 3, 1]  # insert(-1, 4) -> -1 translates to 2
[2, 3, 4, 1]  # insert(-1, 5) -> -1 translates to 3
[2, 3, 4, 5, 1]  # insert(-1, 6) -> -1 translates to 4
[2, 3, 4, 5, 6, 1]  # insert(-1, 7) -> -1 translates to 5
[2, 3, 4, 5, 6, 7, 1]  # insert(-1, 8) -> -1 translates to 6
[2, 3, 4, 5, 6, 7, 8, 1]  # insert(-1, 9) -> -1 translates to 7
[2, 3, 4, 5, 6, 7, 8, 9, 1]  # insert(-1, 10) -> -1 translates to 8
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]