Seek support for new slice syntax PEP.

Colin W. cjwilliams43 at gmail.com
Fri Dec 18 09:50:01 EST 2009


On 17-Dec-09 20:00 PM, Nobody wrote:
> On Mon, 14 Dec 2009 14:18:49 -0500, Terry Reedy wrote:
>
>> Many more people uses range objects (xrange in 2.x). A range object has
>> the same info as a slice object *plus* it is iterable.
>
> This isn't quite true, as a range cannot have a stop value of None, i.e.
> you can't represent [n:] or [:] etc as a range. Similarly for using
> negative stop values for indices relative to the end of the sequence being
> sliced.
>
> Also, aside from the semantics of slice objects themselves, slice notation
> isn't limited to a single slice object; it can also return a tuple of
> slices and values, e.g.:
>
> 	>  numpy.s_[1::2,...,3,4:5:6]
> 	(slice(1, None, 2), Ellipsis, 3, slice(4, 5, 6))
>
> For a single slice, enumerating over a slice with an unspecified stop
> value would be equivalent to itertools.count(). Negative stop values won't
> work.
>
> For a multi-dimensional slice, with everything specified, you would
> probably want to iterate over the cartesian product (i.e. N nested loops
> for an N-dimensional slice). But this won't work if anything other than
> the outermost loop has an unspecified stop value, or if you use an
> ellipsis within a slice.
>
> Oh, and being able to slice a slice could be quite useful, i.e.:
>
> 	[10:90:10][2::2] == [30:90:20]
>
> cf:
> 	>  numpy.arange(100)[10:90:10][2::2]
> 	array([30, 50, 70])
> 	>  numpy.arange(100)[30:90:20]
> 	array([30, 50, 70])
>
You don't say, but seem to imply that the slice components include None.

Section 5.3.3 of the Python doc for 2.6.4 has

The lower and upper bound expressions, if present, must evaluate to 
plain integers; defaults are zero and the sys.maxint, respectively. If 
either bound is negative, the sequence’s length is added to it. The 
slicing now selects all items with index k such that i <= k < j where i 
and j are the specified lower and upper bounds. This may be an empty 
sequence. It is not an error if i or j lie outside the range of valid 
indexes (such items don’t exist so they aren’t selected).

Colin W.



More information about the Python-list mailing list