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

Wayne Werner waynejwerner at gmail.com
Wed Jan 6 16:45:43 CET 2010


On Wed, Jan 6, 2010 at 8:54 AM, spir <denis.spir at free.fr> wrote:

> Hello,
>
> Just found something rather misleading with negative indices:
>
> 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. Well, this can be explained: insertion adds an index, there are
> now 10, so when counting backwards a given index does not point to the same
> position/item anymore than before insertion. Still, it's a bit disturbing.
> What do you think?
> (And: should insert behave so that 0 actually is at index -3, meaning
> insert it after 7?)
>
> (No issue with positive indices, indeed.)
>

I think it may just be an issue with misunderstanding what the insert does:

>>> help(list.insert)

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

When you insert(-3, 0) you are inserting 0 before index -3. When it says
"before" it has nothing to do with the direction of travel.

And when you say there's no issue with positive indices, take a look at this
case:

In [6]: s = [1,2,3]

In [7]: s[0]
Out[7]: 1

In [8]: s.insert(0,0)

In [9]: s[0]
Out[9]: 0

(ignoring mathematical considerations about the sign of 0)

You get a different value at the same position.

It seems that your confusion lies with this statement:
"insertion adds an index"

which it doesn't - insertion adds an object to your list. It's a fundamental
difference - the computer stores objects, and if we want to access that
object we have to know where it's stored. In your first case, 7 and 6 are
stored in the positions 3 and 4 from the end of the list. When you
insert(-3, 0) you're shifting everything before -3 and putting 0 in the spot
before (at least that's how I think of it. How python actually implements
lists is probably different.).

Does that make sense? (and if I've explained it incorrectly, feel free to
correct me!)
HTH,
Wayne
-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100106/a2644370/attachment.htm>


More information about the Tutor mailing list