Slicing in Python 2.3a2

Robin Munn rmunn at pobox.com
Wed Apr 2 12:26:23 EST 2003


Sébastien Keim <s.keim at laposte.net> 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)
> 
> Python 2.3 add a new argument to slice wich can for sample be used to
> get only the items at positive indexes:
> >>> A[::2]
> [0, 2, 4, 6, 8]

I think of the parts of the slice as "start, stop, step", and an empty
start *or* stop means "start/stop at the end of the sequence". *Which*
end depends on what direction you're going. For instance, the above
means "start at one end, stop at one end, step forward by twos". The
"start" end is the beginning, the "stop" end is the end.

Oh dear, I'm using the word "end" for two different meanings here. Let
me disambiguate by using the word "edge" instead.

   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   ^                            ^
   \- "front" edge              \- "back" edge

So A[::2] means "start at an edge, stop at an edge, step forward by 2".
Since the step is forward, the slice will start at the front edge and
stop at the back edge.

> This works also for subslices: A[x:y:z] is equal to A[x:y][::z]
> >>> A[1::2]
> [1, 3, 5, 7, 9]

Start at index 1, stop at an edge, step forward by 2. Since the step is
forward, the slice will stop at the back edge.

> With a negative value you can reverse a list:
> >>> A[::-1]
> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Start at an edge, stop at an edge, step backward by 1. Since the step is
backward, the slice will start at the back edge and stop at the front
edge.

> But I don't understand the result for a subslice with a negative third 
> argument:
> >>> A[1::-1]
> [1, 0]

Start at index 1, stop at an edge, step backward by 1. Since the step is
backward, the slice will stop at the front edge.

> Intuitively, I expected to get:
> >>> A[1:][::-1]
> [9, 8, 7, 6, 5, 4, 3, 2, 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?

The semantics I illustrated above appear to work for all the cases I
know of. Do you know of any counterexamples?

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list