python - python 中的 list.insert() 实际上做了什么?

标签 python python-3.x list insert

我有这样的代码:

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”,它也会在第一个可用索引处插入。那么“插入”是如何做出决定的呢?

最佳答案

来自Python3 doc :

list.insert(i, 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 将追加到列表中。

如果您深入研究 Python implementation您可以在执行插入操作的 ins1 函数中找到以下内容:

if (where > n)
    where = n;

所以基本上 Python 会将你的索引最大化到列表的长度。

关于python - python 中的 list.insert() 实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614538/

相关文章:

python - 如何获取导致 any() 返回 True 的值?

python - 用 pythons 内置的 map 函数替换函数

python - (Python : discord. py)错误 : Could not build wheels for multidict, 使用 PEP 517 且无法直接安装的 yarl

python - 为什么 python 的 "gc.collect()"没有按预期工作?

mysql - 如何将子查询中的字符串连接到mysql中的一行?

algorithm - 这种类型的二进制搜索有名称吗?

python - AWS Lambda : OpenBLAS WARNING - could not determine the L2 cache size on this system, 假设为 256k - 使用 Google 自定义搜索 API 时

python - 如何在Python中连接单词和整数?

python - 逻辑回归得到 sm.Logit 值(python,statsmodels)

java - 多态性:为什么使用 "List list = new ArrayList"而不是 "ArrayList list = new ArrayList"?