A suggestion for a possible Python module

Alex Martelli aleax at aleax.it
Wed Mar 5 06:41:07 EST 2003


Terry Reedy wrote:
   ...
> "Alex Martelli" <aleax at aleax.it> wrote in message
> news:oK49a.5039$zo2.154480 at news2.tin.it...
>> Yes, and the boundaries play strangely...:
>>
>> >>> x = list('arrivederci')
>> >>> x[2:7] = x[7:2:-1]
>> >>> ''.join(x)
>> 'aredevierci'
>> >>>
>>
>> x[2:7] being 'rived', one would expect 'ardevirerci' -- but to
>> get that one needs an ample application of -1's, alas...:
>>
>> >>> x = list('arrivederci')
>> >>> x[2:7] = x[7-1:2-1:-1]
>> >>> ''.join(x)
>> 'ardevirerci'
>> >>>
>>
>> Goofy, slow, and error-prone, I think there's little to be said
>> for this idiom (x[start:stop] = x[stop-1:start-1:-1] in the
>> general case).
> 
> As near as I can tell, the 19 February 2003 2.3a2 Ref Man, Section
> 5.3.3 Slicings, (on python.org) has not been updated to specify the
> long_slice behavior when *not* used as a dict key but used for seq
> access.  If so, there is no way to tell if behavior above is intended
> or is a bug (except by analogy with Numeric behavior, which I am not
> familiar with).

I think a more familiar analogy, although not explicitly pointed
out in the language reference AFAIK, is that slices are meant to
correspond to the same indices that range or xrange would produce
when called with the same start, stop and step parameters (net
of issues with missing or negative parameters, or slicings of a
too-short sequence).

>>> range(7,2,-1)
[7, 6, 5, 4, 3]
>>>

It would be weird, astonishing, and unPythonic in the extreme if
(assuming 'whatever' is a sequence with a length of at least 8)
whatever[7:2:-1] didn't produce a subsequence of 'whatever' that
starts with whatever[7] and end with whatever[3], NOT reaching all
the way to whatever[2] -- just like whatever[2:7] produces a
subsequence that starts with whatever[2] and ends with whatever[6],
not reaching all the way to whatever[7].

so, whatever[start:stop] = whatever[stop:start:-1] "CANNOT:
reverse a subsequence in place without breaking all kinds of
expected regularities between slices and range/xrange...!


Alex





More information about the Python-list mailing list