list.insert()在python中实际做什么? [英] What does list.insert() in actually do in python?

查看:54
本文介绍了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

因此,即使我要求python在索引"2"处插入"1",它也会在第一个可用索引处插入.那么插入"如何做出决定?

So even if I ask python to insert '1' at index '2', it inserts at the first available index. So how does 'insert' makes the decision?

推荐答案

来自 Python3doc :

list.insert(i,x)

在给定位置插入项目.首先参数是要插入的元素的索引,因此a.insert(0,x)插入列表的最前面,而a.insert(len(a),x)等同于a.append(x).

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

未提及的是,您可以提供超出范围的索引,然后Python将追加到列表中.

What is not mentionned is that you can give an index that is out of range and Python will then append to the list.

如果您深入研究 Python实现,则会发现进行插入的 ins1 函数中的以下内容:

If you dig into the Python implementation you find the following in the ins1 function that does the insertion:

if (where > n)
    where = n;

因此,基本上,Python将使索引的最大长度达到列表的长度.

So basically Python will max out your index to the length of the list.

这篇关于list.insert()在python中实际做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆