extended slicing and negative stop value problem

Chris Rebert clp2 at rebertia.com
Sun Aug 21 18:16:21 EDT 2011

On Sun, Aug 21, 2011 at 10:27 AM, Max <maxmoroz at gmail.com> wrote:
> On Aug 20, 1:40 pm, Steven D'Aprano <steve
> +comp.lang.pyt... at pearwood.info> wrote:
>> On Sat, Aug 20, 2011 at 7:20 PM, Max Moroz <maxmo... at gmail.com> wrote:
>> > Would it be a good idea to change Python definition so that a[10, -1, -1]
>> I presume you mean slice notation a[10:-1:-1].
>> > referred to the elements starting with position 10, going down to the
>> > beginning?
>> The usual advice is to do your slicing twice, reversing it the second time:
>> a[0:11][::-1]
>> # Instead of a[10:-1:-1], which looks like it should work, but doesn't.
> It works nicely, but it is 1.3 times slower in my code (I am surprised
> the interpreter doesn't optimize this).

That would require CPython to assume certain slicing semantics for all
types (which it can't) or to check for this very specific case at
runtime (which would slow down all other [list] slicing operations).

A smarter implementation such as PyPy could indeed theoretically
optimize this case though.


More information about the Python-list mailing list