[Tutor] list.insert(<negative index>)

Alan Gauld alan.gauld at btinternet.com
Wed Jan 6 20:25:17 CET 2010


"spir" <denis.spir at free.fr> wrote

> s = [1,2,3,4,5,6,7,8,9]
> print s, s[-3], s[-4] # [1, 2, 3, 4, 5, 6, 7, 8, 9] 7 6
> s.insert(-3, 0)
> print s, s[-3], s[-4] # [1, 2, 3, 4, 5, 6, 0, 7, 8, 9] 7 0
>
> So, I did insert 0 at index -3, but s[-3] is still 7, & 0 is in fact at 
> index -4.

Seems reasonable. insert() inserts before the referenced item so
I would expect it to appear at -4. If it did otherwise you would get a
different result depending on whether you used positive or negative
indexing - which would be really wierd!

> Well, this can be explained: insertion adds an index,

It doesn't so much add an index - there are no such things as
indexes per se they are just references into the list - as insert
an item before the item referenced. As a consequence all
subsequent items will inevitably acquire a new relative position
so the index used to locate them will change. But the index is
not a property opf the list item, it is simple a location indicator.

> when counting backwards a given index does not point
> to the same position/item anymore than before insertion.

The same applies when using positive indexes:

>>> L = [0,1,2,3,4,5,6]
>>> L.insert(4,9)
>>> L
[0, 1, 2, 3, 9, 4, 5, 6]

4 is now at index 5 and 9 is at 4.

But that is not because we asked the list to create an item with
an index of 4, rather we asked it to insert an item before the item
at position 4. That accidentally leaves it with an index of 4.

It might seem like a philospohical point but it is the explanation
that makes insert consistent for positive and negative indexes.
And its how help() describes the action:

>>> help(L.insert)
Help on built-in function insert:

insert(...)
    L.insert(index, object) -- insert object before index

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list