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

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?

解决方案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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值