What does list.insert() in actually do in python?

对着背影说爱祢 提交于 2020-12-26 11:11:22

问题


I have code like this:

squares = []
for value in range(1, 5):
    squares.insert(value+1,value**2)

print(squares)
print(squares[0])
print(len(squares))

And the output is :

[1, 4, 9, 16]

1

4

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?


回答1:


From the 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).

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

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

if (where > n)
    where = n;

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




回答2:


Basically, it's similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.



来源:https://stackoverflow.com/questions/47614538/what-does-list-insert-in-actually-do-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!