[Python-ideas] [Python-Dev] Inclusive Range

Dave Angel davea at ieee.org
Mon Oct 11 12:25:49 CEST 2010

  On 2:59 PM, Antoon Pardon wrote:
> On Sat, Oct 09, 2010 at 01:37:03AM +0000, Steven D'Aprano wrote:
> <snip>
>> But the point was that Antoon claimed that there is no numeric value for
>> the end position that will include L[0] in the reversed slice. My example
>> shows that this is not correct.
> I stand by that claim. I think it was fairly obvious that what I meant
> was that it was impossible to give such a numeric value that would work
> with arbitrary L.
> if L2 == list(reversed(L1)) and a and b are in the range 1<  x<= len(L),
> we have the following invariant.
>    L1[a:b] == L2[b-1:a-1:-1]
> However this no longer works if either nr is 0. That means that if a and
> be are computed values, that may return 0 to indicate which slice you
> want; that if you want the reversed slice, there is no straightforward
> way to get that reversed slice with extended slice notation.
Rather than worrying about how to get from one kind of slice to another, 
consider that for both forward and reversed slices, there are edge 
conditions that are painful.  For forward slices, that's when you 
sometimes want the end of the list, and sometimes don't.  The expression 
that says how close to the end you want can be -1, -2, etc.  But there's 
no -0 notation to say "up and including the last element".  For that, 
you just omit the ending point, or use the length.

Similarly for reverse slice that may end at the beginning.  In order to 
generalize it, you have to include the length in your expression.

I think the fact that there are two other idioms that handle it makes 
the "problem" mostly irrelevant.  Either reverse the slice after taking 
it, or use a second slice to chop off zero or more items from the end.


More information about the Python-list mailing list