[Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me
Cameron Simpson
cs at zip.com.au
Sat Jan 16 00:32:34 EST 2016
On 15Jan2016 23:05, boB Stepp <robertvstepp at gmail.com> wrote:
>On Fri, Jan 15, 2016 at 10:53 PM, Cameron Simpson <cs at zip.com.au> wrote:
>>>>>> things.insert(-1, 'What the heck?!?')
>>>>>> things
>>>
>>> [0, 'Hmm...', 3, 'WhackABunny', 6, 'What the heck?!?', '?']
>>>
>>> "...at the index..." to me would mean that 'What the heck?!?' should
>>> become the last item in the list. Again, the interpreter help gave
>>> what I was expecting.
>>
>>
>> To me it means "insert 'x' so that its index is 'i'".
>
>But that's my point! In my example x (here 'What the heck?!?') is
>*not* at index i (here, -1). Instead it winds up at index -2. But
>this fits in perfectly with the interpreter help, since it winds up
>*before* index i (-1).
Ah, but -1 isn't the "real" index. It is a convenient value for computing the
real index if you want to figure things out from the end of the list instead of
the start. In your example above, the real index is 5. As you would get from
things.index('?') before the insert. So your insert really means:
things.insert(5, 'What the heck?!?')
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list