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

前端 未结 7 835
天命终不由人
天命终不由人 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 01:05

    Comments by Guido van Rossum, creator of Python, on the python-dev mailing list (check the September 2014 archives; in my experience, the exact URLs for specific messages have a way of changing from time to time), in response to OP's crossposting of this question on that list:

    On Mon, Sep 15, 2014 at 3:46 PM, Mark Lawrence wrote:

    I assume it's based on the concepts of slicing. From the docs "s.insert(i, x) - inserts x into s at the index given by i (same as s[i:i] = [x])".

    Ah, right. It matches thigs like s[100:] which is the empty string if s is shorter than 100.

    And in another response:

    This functionality has existed since the earliest days of Python, and even if we all agreed it was wrong we couldn't change it -- it would just break too much existing code. I can't quite remember why I did it that way but it was definitely a conscious choice; probably some symmetry or edge case. (Note that it works this way at the other end too -- a.insert(-100, x) will insert x at the beginning of a, if a has fewer than 100 elements.)

    Ultimately, this kind of thing is a design decision. There are almost always competing concerns, and you can never find something that will be intuitive to everyone. Just look at how many ways different languages handle a concept as fundamental as True and False (in some languages, they are identical to the numbers 1 and 0; in some languages any nonzero is True; in some languages True and False are identical to the characters '1' and '0' (yes, really!); in some languages they are completely incompatible with numbers or any other not-strictly-Boolean type; in some languages empty containers are False, in others they are True; the choices go on and on). Or look at nil/null/None, which also have interesting interactions with Booleans and other calculations. Some languages even have Maybe.

    The way Python handles list insertion is handy in some situations, and enough people found it useful that they've written code that makes use of and depends upon insertion behaving this way. Perhaps the documentation could be a little clearer, but it's really not that unclear; and in any case, once you try it, you see what it does, and you write your Python code accordingly.

提交回复
热议问题