Seek support for new slice syntax PEP.

Colin W. cjwilliams43 at gmail.com
Mon Dec 14 13:40:38 EST 2009


On 14-Dec-09 13:03 PM, Dave wrote:
> Just as sets may now be written as {3,'hi'}, I propose that slices
> should be available using [start:end] syntax.  Following example comes
> from projecteuler.net problem 166.  The Numeric community would also
> like this, as would the general python user.  The slice notation would
> require one ":" between the brackets to differentiate it from a list,
> which is similar to the set notation requirement that disambiguates it
> from a dictionary.
>
> Several times now I've wanted python slice notation.  Perhaps I'll
> write a Python Enhancement Proposal.  I stored slices of vector array
> entries to add
>
>
> edge = 4
> indexes = []
> n = edge
> nn = n**2
> for i in range(edge):
>      indexes.extend([
>          slice(i*n,(i+1)*n,1),       # rows
>          slice(i,nn,n),              # cols
>          ])
>
> row_slices = indexes[0::2]
> col_slices = indexes[1::2]
> slash = slice(n-1,n*(n-1)+1,n-1)
> backslash = slice(0,nn,n+1)
>
>
> Which could have been written in a manner completely consistent with
> other python shorthand notations and for which python "cannot
> possibly" use the notation for some other purpose,
>
>
> edge = 4
> indexes = []
> n = edge
> nn = n**2
> for i in range(edge):
>      indexes.extend([
>          [i*n: (i+1)*n]                  # rows
>          [i: nn: n],                      # cols
>          ])
>
> row_slices = indexes[0::2]
> col_slices = indexes[1::2]
> slash = [n-1: n*(n-1)+1: n-1]
> backslash = [0: nn: n+1]

Yes, we know that PEP 3003 applies but I see no harm in discussing 
possible enhancements.

The existing slice seems a little different from what you are proposing:
An object usually containing a portion of a sequence. A slice is created 
using the subscript notation, [] with colons between numbers when 
several are given, such as in variable_name[1:3:5].
or:
Slice objects
Slice objects are used to represent slices when extended slice syntax is 
used. This is a slice using two colons, or multiple slices or ellipses 
separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. 
They are also created by the built-in slice() function.

If your scheme flies, would it be practicable to use the same syntax
as a range generator?

range(i, j, k)  => i:j:k

so range(10, 2) => :10:2

i.e. we could write for i in :10:2:

or the more common:
range(10)  => :10

Colin W.





More information about the Python-list mailing list