List insert at index that is well out of range - behaves like append

前端 未结 7 834
天命终不由人
天命终不由人 2020-12-11 00:37

I had a list

 a = [1, 2, 3]

when I did

a.insert(100, 100)

[1, 2, 3, 100]

as list was originally of siz

7条回答
  •  执笔经年
    2020-12-11 00:49

    Instead of contrasting insert to item assignment, it's more analogous to slice assignment, since both change the size of the list.

    >>> a = [1, 2, 3]
    >>> a[100:100] = [100]
    >>> a
    [1, 2, 3, 100]
    

    Slices also don't raise IndexError, and so is consistent with:

    a.insert(100, 100)
    

提交回复
热议问题