[Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me

Steven D'Aprano steve at pearwood.info
Sun Jan 17 02:38:42 EST 2016


On Sat, Jan 16, 2016 at 01:19:16PM +0100, Peter Otten wrote:
> 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. 

Half-open at the start or the end? :-)

You're right, "half-open intervals" (open at the end) is also a good way 
of thinking about it. It certainly helps with things like range(), which 
don't involve slicing/cutting. You just memorize the the start value is 
included and the end value is not.

If you think of indexes falling between elements, and slicing along 
those gaps, then the natural consequence is a half-open interval. Take 
mylist[1:6] for example:


          0 1 2 3 4 5 6 7 8
mylist = [ a b c d e f g h ]
            |         |
        cut here    and here


By cutting *between* a and b, and f and g, you naturally get a half open 
interval: mylist[1] is included, but mylist[6] is not.

But if you think of indexes being aligned with the items themselves, you 
need to memorize a special rule "do I include the item or not?":


           0 1 2 3 4 5 6 7
mylist = [ a b c d e f g h ]
             |         |
          include   exclude
           this      this



> > 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.

Oops, so I did. You're absolutely right.

mylist = [ 100, 200, 300, 400, 500 ]
indexes:  ^    ^    ^    ^    ^   ^
          -5   -4   -3   -2  -1   

The last index ought to be "-0" in some sense, but of course that's just 
zero which is the first index. So as you say:


> Slightly related is a problem that comes up in practice; you cannot specify 
> "including the last item" with negative indices:

But you can do so by leaving the end index blank:

py> mylist = [ 100, 200, 300, 400, 500 ]
py> mylist[-2:-1]
[400]
py> mylist[-2:0]
[]
py> mylist[-2:]
[400, 500]



-- 
Steve


More information about the Tutor mailing list