[Python-Dev] Negative index in insert()
Tim Peters
tim.one@home.com
Sun, 26 Aug 2001 02:14:15 -0400
[Eric S. Raymond]
> Given
>
> >>> a = [1, 2, 3, 4]
>
> because
>
> >>> a[-2]
> -3
>
> 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]
>
> In fact I think this may be the nastiest surprise Python has
> handed me since I started using it.
I never noticed it, but agree it's strange. Did you open a feature request
on SourceForge? Note that array objects (created by the array module) share
this behavior.
> The reference manual says "same as s[i:i] = [x] if i >= 0" which
> of course doesn't cover the i < 0 case.
Which formally means its behavior is undefined.
> David Beasley's reference says "Inserts x at index i" which sounds like
> the behavior I was expecting but didn't get.
Ya, so file a bug report with David <wink>.
> Is this a deliberate design choice, an oversight, or a plain bug? If
> it's a choice, it's damn poorly documented -- this deserves at least a
> footnote in the list methods table. If it's an oversight or bug, I
> volunteer to fix it.
Only Guido *may* be able to say for sure. Plausible: the behavior for i<0
was deliberate at the start, and when Python *grew* negative indices (it
didn't always accept them), fear of incompatibility prevented changing
.insert behavior (in the other cases where negative indices "grew a
meaning", the old behavior was to raise an exception; but .insert accepted
them silently).
Digging thru CVS, the current behavior for i<0 has always been that way
(since listobject.c rev 1.1); and the "if i >= 0" qualifier was added to
libtypes.tex a bit over 6 years ago, with checkin comment
correct description of list.insert()
Hard call! I agree it should change, but if it breaks code the "but it was
formally undefined" comeback doesn't really warm peoples' hearts.
first-one-to-suggest-a-future-stmt-dies-ly y'rs - tim