[Python-Dev] Re: Negative index in insert()

Ka-Ping Yee ping@lfw.org
Sun, 26 Aug 2001 02:39:55 -0700 (PDT)

Eric S. Raymond wrote:
> >>> a = [1, 2, 3, 4]
> I expected that a.insert(-2, 0) would yield [1, 2, 0, 3, 4].  It was a
> rude shock to discover that
> >>> a
> [0, 1, 2, 3, 4]

If this is fixed, i think we should do a complete job of it and
make sure exceptions are raised when the index is out of range.

Notice (in current Python):

    >>> a = [1, 2, 3, 4]
    >>> a.insert(999, 0)
    >>> a
    [1, 2, 3, 4, 0]
    >>> a.insert(-999, 0)
    >>> a
    [0, 1, 2, 3, 4, 0]

So what's happening is that Python is silently clipping the
index to [0..n].  To bring this in line with indexing behaviour,
it should not only interpret values in the range [-n..n], but also
raise IndexError when the value is outside of [-n..n].  (Compare
to pop() -- the behaviour i'm suggesting is exactly what pop()
does, except that the range for pop() is [-n..n-1].)

This has the potential for breaking code, and so the transition
should probably be done with a minor-version's worth of warning,
but i think if we're going to change it we should make it right.

When this is done, i believe we'll be down to exactly two ways of
handling sequence indices --

    (a) x and y are silently clipped to [-n..n-1]
        *only* in an [x:y]-style slice

    (b) in all other cases, an IndexError is raised if the
        index is out of range

and these two cases are easy to separate and explain, and all
will be consistent in its interpretation of negative numbers.
Such simplicity would be nice to have.

-- ?!ng

"Computers are useless.  They can only give you answers."
    -- Pablo Picasso