[Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me
Peter Otten
__peter__ at web.de
Sat Jan 16 07:19:16 EST 2016
Steven D'Aprano wrote:
> But slices are slightly different. When you provide two indexes in a
> slice, they mark the gaps BETWEEN items:
The other explanation that Python uses half-open intervals works for me.
> Now, what happens with *negative* indexes?
>
> mylist = [ 100, 200, 300, 400, 500 ]
> indexes: ^ ^ ^ ^ ^ ^
> -6 -5 -4 -3 -2 -1
>
> mylist[-5:-2] will be [200, 300, 400]. Easy.
>>> mylist = [ 100, 200, 300, 400, 500 ]
>>> mylist[-5:-2]
[100, 200, 300]
Off by one, you picked the wrong gaps.
Slightly related is a problem that comes up in practice; you cannot specify
"including the last item" with negative indices:
>>> for i in reversed(range(len(mylist))):
... print(mylist[:-i])
...
[100]
[100, 200]
[100, 200, 300]
[100, 200, 300, 400]
[]
A simple fix is
>>> for i in reversed(range(len(mylist))):
... print(mylist[:-i or None])
...
[100]
[100, 200]
[100, 200, 300]
[100, 200, 300, 400]
[100, 200, 300, 400, 500]
The hard part is to remember to test whenever a negative index is
calculated.
More information about the Tutor
mailing list