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

前端 未结 2 1009
长发绾君心
长发绾君心 2021-01-24 18:26

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))
<         


        
2条回答
  •  庸人自扰
    2021-01-24 18:40

    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.

提交回复
热议问题