list.insert()在python中实际做了什么?

我有这样的代码:list.insert()在python中实际做了什么?

squares = [] 

for value in range(1, 5):

squares.insert(value+1,value**2)

print(squares)

print(squares[0])

print(len(squares))

,输出是:

[1, 4, 9, 16] 

1

4

所以,即使我问蟒蛇索引“2”插入“1”,它插入第一个可用指数。那么'插入'如何做出决定?

回答:

从Python3 doc:

list.insert(i, x)

在指定位置插入一个元素。第一个参数 是之前插入的元素的索引,因此 a.insert(0,x)插入列表的前面,并且a.insert(len(a), x)等同于.append(X)。

什么没有提到的是,你可以给一个超出范围的索引,然后Python将追加到列表中。

如果你深入到Python implementation您发现ins1函数,它插入如下:

if (where > n) 

where = n;

所以基本上Python会最大程度的发挥你的索引列表的长度。

以上是 list.insert()在python中实际做了什么? 的全部内容, 来源链接: utcz.com/qa/259180.html

回到顶部