slicings: 3 questions
robert.kern at gmail.com
Thu Jan 29 22:41:28 CET 2009
On 2009-01-29 15:33, Alan G Isaac wrote:
>> On Thu, Jan 29, 2009 at 10:01 AM, Alan G Isaac <alan.isaac at gmail.com>
>>> 2. It seems that slice objects and range objects are
>>> awfully similar in many ways. Is this "appearance only",
>>> or was there any discussion of unifying them?
>>> Curious for insight...
> On 1/29/2009 1:37 PM Chris Rebert apparently wrote:
>> Wouldn't really be possible, IMHO. True, they both have notions of
>> start, stop, and step, but slices don't make sense as ranges without
>> knowing the length of the container.
> Slices seem somewhat more general than ranges.
>> For example, take the slice
>> `1:-2:1`. This is somewhat equivalent to range(1, -2, 1). However,
>> since -2 < 1 (stop < start ) and 1 (the step) is positive, the range
>> is nonsensical.
> Or rather, it makes sense, but is empty.
> But I take your point.
> However, I would turn it around slightly and ask:
> when is it not the case that
> range(*slice(start,stop,step).indices(stop)) != range(stop,start,step)
> If there are no interesting cases, then it seems
> that range might derive from slice.
> Just curious...
It's possible that it *could*, but there's also no real benefit to doing so.
>> You have to replace all the negative indices with calculated positive
>> indices first in order to have a sensical range(), in this case,
>> replacing the stop of -2 with len(container)-2.
>> Also, more fundamentally, Python is liberal in what it allows for the
>> parts of slices, so unifying slices with ranges would break code. For
>> example, Python is perfectly happy if I go slice("a",,object), none
>> of which are even numbers.
> Ah, this is new in Python 3 I take it?
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
slice('a', , <type 'object'>)
> I was not aware of this. Use case?
It allows (ab)uses like numpy.mgrid:
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list