Bug in slice type

Steven Bethard steven.bethard at gmail.com
Thu Aug 18 11:17:20 EDT 2005


I wrote:
> I wanted to say something about what happens with a negative stride, to 
> indicate that it produces (9, -1, -2) instead of (-1, -11, -2), but I 
> wasn't able to navigate the Python documentation well enough.
> 
> Looking at the Language Reference section on the slice type[1] (section 
> 3.2), I find that "Missing or out-of-bounds indices are handled in a 
> manner consistent with regular slices." So I looked for the 
> documentation of "regular slices".  My best guess was that this meant 
> looking at the Language Reference on slicings[2].  But all I could find 
> in this documentation about the "stride" argument was:
> 
> "The conversion of a proper slice is a slice object (see section 3.2) 
> whose start, stop and step attributes are the values of the expressions 
> given as lower bound, upper bound and stride, respectively, substituting 
> None for missing expressions."
> 
> This feels circular to me.  Can someone help me find where the semantics 
> of a negative stride index is defined?

Well, I couldn't find where the general semantics of a negative stride 
index are defined, but for sequences at least[1]:

"The slice of s from i to j with step k is defined as the sequence of 
items with index x = i + n*k such that 0 <= n < (j-i)/k."

This seems to contradict list behavior though.
     range(10)[9:-1:-2] == []
But the values of n that satisfy
     0 <= n < (-1 - 9)/-2 = -10/-2 = 5
are 0, 1, 2, 3, 4, corresponding to the x values of 9, 7, 5, 3, 1.  But
     [range(10)[x] for x in [9, 7, 5, 3, 1]] == [9, 7, 5, 3, 1]
Does this mean that there's a bug in the list object?

STeVe

[1] http://docs.python.org/lib/typesseq.html



More information about the Python-list mailing list