[New-bugs-announce] [issue28882] RFC: Slice confusing with negative strides and the 0th element.

steven Michalske report at bugs.python.org
Tue Dec 6 00:06:40 EST 2016


New submission from steven Michalske:

The slicing and using inputed math is is necessary to provide a special case to make the code behave as expected.

Unless I'm missing something.  Like we can't do this, as we loose negative indexing from the end of the file?

Let's take the following example, byte swapping 32bit integers.

a = [0,1,2,3,4,5,6,7]

print([a[x] for x in [slice(y+3, y-1 if y > 1 else None, -1) for y in range(0, len(a), 4)]])
[[], [7, 7, 6, 5]]

Catching my explicit case, I changed my code to:
print([a[x] for x in [slice(y+3, y-1 if y > 1 else None, -1) for y in range(0, len(a), 4)]])
[[3, 2, 1, 0], [7, 6, 5, 4]]

Life proceeds as I am explicit, but now I have a conditional check that is slowing me down...

It appears that -1 is being considered the last element in the set.
This was surprising, as I couldn't use simple math to byte swap, I needed to pass None instead of -1

It appears PySlice_GetIndices in file cpython/Objects/sliceobject.c always 
adds length if stop < 0 regardless to start and step.

    if (r->stop == Py_None) {
        *stop = *step < 0 ? -1 : length;
    } else {
        if (!PyLong_Check(r->stop)) return -1;
        *stop = PyLong_AsSsize_t(r->stop);
        if (*stop < 0) *stop += length;   # <-- Issue here?
    }


It seems that there is some undocumented logic and behavioral decisions.

Was it explicitly decided that a negative stop and negative stride
e.g. 
In [46]: a[3:0:-1]
Out[46]: [3, 2, 1]

In [47]: a[3:-1:-1]
Out[47]: []

Not [3,2,1,0]  (My least surprising value...)

Because -1 is based on len(a).

I expected that with a positive start, and a negative stride that the -1 case would be considered include 0.

In other code...
[4:-1:-1] == [4:None:-1]
Not
[4:-1:-1] == [4:len(a)-1:-1]
Especially when len(a)-1 > start

I understand that this is behavioral, but it is confusing...

Discussion?

----------
messages: 282500
nosy: hardkrash
priority: normal
severity: normal
status: open
title: RFC: Slice confusing with negative strides and the 0th element.
type: behavior
versions: Python 3.5

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue28882>
_______________________________________


More information about the New-bugs-announce mailing list