[Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me
Cameron Simpson
cs at zip.com.au
Fri Jan 15 23:53:51 EST 2016
On 15Jan2016 22:20, boB Stepp <robertvstepp at gmail.com> wrote:
>At https://docs.python.org/3.4/library/stdtypes.html#sequence-types-list-tuple-range
>it states:
>
>"s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])"
>
>I find this confusing. First, at the interpreter, whenever I type in:
>
>>>> things
>[0, 'Hmm...', 3, 'WhackABunny', 6, '?']
>>>> things[-1:-1]
>[]
>>>> things[0:0]
>[]
>
>I always get an empty list, which is actually what I was expecting, so
>I do not see how s[i:i] can ever equal [x].
It isn't an equality test (==), it is an assignent. It is saying "set the zero
length sequence at index i to the one element sequence [x]".
>The second thing I find puzzling is the docs say x is inserted at
>position i, while in the interpreter:
>
>>>> help(list.insert)
>Help on method_descriptor:
>
>insert(...)
> L.insert(index, object) -- insert object before index
>
>The "...insert object before index" makes sense to me, but "...inserts
>x into s at the index given by i..." does not because:
Personally I'd rather it said "insert object at index". For "before" I'd need
something longer, like "insert object before the elements from index onward".
>>>> 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'".
>Am I just being dense or are the docs in this instance confusing?
They may be a bit confusing, though I do think you're misreading the "=" bit at
the top.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list