Negative array indicies and slice()

Ian Kelly ian.g.kelly at gmail.com
Wed Oct 31 17:20:33 EDT 2012


On Wed, Oct 31, 2012 at 7:42 AM, Andrew Robinson
<andrew3 at r3dsolutions.com>wrote:

> Then; I'd note:  The non-goofy purpose of slice is to hold three data
> values;  They are either numbers or None.  These *normally* encountered
> values can't create a memory loop.
> So, FOR AS LONG, as the object representing slice does not contain an
> explicit GC pair; I move that we mandate (yes, in the current python
> implementation, even as a *fix*) that its named members may not be assigned
> any objects other than None or numbers....
>
> eg: Lists would be forbidden....
>
> Since functions, and subclasses, can be test evaluated by int(
> the_thing_to_try ) and *[] can too,
> generality need not be lost for generating nothing or numbers.
>

PEP 357 requires that anything implementing the __index__ special method be
allowed for slicing sequences (and also that __index__ be used for the
conversion).  For the most part, that includes ints and numpy integer
types, but other code could be doing esoteric things with it.

The change would be backward-incompatible in any case, since there is
certainly code out there that uses non-numeric slices -- one example has
already been given in this thread.
And more wonderful yet, when I do extended slice replacement -- it gives me
results beyond my wildest imaginings!


> >>> a=[0,1,2,3,4,5]
> >>> a[4:5]=range( 0, 3 ) # Size origin=1, Size dest =3
> >>> a
> [0, 1, 2, 3, 0, 1, 2, 5]  # Insert on top of replacement
> >>>
> But !!!NOT!!! if I do it this way:
> >>> a[4]=range( 0, 3 )
> >>> a
> [0, 1, 2, 3, range(0, 3), 1, 2, 5]
> >>>
>

That's nothing to do with range or Python 3.  It's part of the difference
between slice assignment and index assignment.  The former unpacks an
iterable, and the latter assigns a single object.  You'd get the same
behavior with lists:

>>> a = list(range(6))
>>> a[4:5] = list(range(3))
>>> a
[0, 1, 2, 3, 0, 1, 2, 5]
>>> a = list(range(6))
>>> a[4] = list(range(3))
>>> a
[0, 1, 2, 3, [0, 1, 2], 5]

Slice assignment unpacks the list; index assignment assigns the list itself
at the index.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121031/e5e9d6f2/attachment.html>


More information about the Python-list mailing list