Extended slices and indices

Robert Kern robert.kern at gmail.com
Sat Sep 23 21:18:24 EDT 2006


GavinCrooks at gmail.com wrote:
> The indices method of slice doesn't seem to work quite how I would
> expect when reversing a sequence.
> 
> For example :
>>>> s = '01234'
>>>> s[::-1]
> '43210'
>>>> s[slice(None,None,-1) ]
> '43210'
> 
> So a slice with a negative step (and nothing else) reverses the
> sequence. But what are the
> corresponding indices?
>>>> slice(None,None,-1).indices(len(s))
> (4, -1, -1)
> 
> That looks O.K. The start is the last item in the sequence, and the
> stop is one before the beginning of the sequence. But these indices
> don't reverse the string:
>>>> s[4:-1:-1]
> ''
> 
> Although they give the correct range:
>>>> range( 4, -1,-1)
> [4, 3, 2, 1, 0]
> 
> It would appear that there is no set of indices that will both reverse
> the string and produce the correct range!
> 
> Is this a bug or a feature?

I'd say bug in the .indices() method. The meaning of [4:-1:-1] is unavoidable 
different than [::-1] since the index -1 points to the last element, not the 
imaginary element before the first element. Unfortunately, there *is* no 
concrete (start, stop, step) tuple that will emulate [::-1].

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list