Slicing in Python 2.3a2
Dave Benjamin
ramen at lackingtalent.com
Tue Apr 1 10:54:50 EST 2003
In article <mailman.1049200983.30254.python-list at python.org>,
Sébastien Keim wrote:
> I have some troubles to understand how work slicing in python 2.3.
> In my examples, I will use the following list:
> >>> A = range(10)
>
> ...
>
> But I don't understand the result for a subslice with a negative third
> argument:
> >>> A[1::-1]
> [1, 0]
> Intuitively, I expected to get:
> >>> A[1:][::-1]
> [9, 8, 7, 6, 5, 4, 3, 2, 1]
You can get this with A[:0:-1].
> The numarray package has the same behavior, so I guess it's intentional.
> >>> import numarray
> >>> numarray.array(range(10))[1::-1]
> array([1, 0])
>
> Then what is the real semantic for this third argument?
I think it makes sense if you think in terms of "start", "stop", and "step".
The step amount represents the value that is added to the implicit counter
with each iteration. I think that the confusion actually comes from the
defaults for start and stop if they are not supplied. It seems from your
example (and the [::-1] form) that the defaults for start and stop are
swapped if the step is negative.
HTH,
Dave
More information about the Python-list
mailing list