Assignment to slice

James Henderson james at logicalprogression.net
Wed Jan 21 14:50:23 EST 2004


On Wednesday 21 January 2004 7:15 pm, Rich Krauter wrote:
> I see your point. However I could be wrong, but I
> don't know if what you say is really the case, since
> negative indexes are just shorthand for
>
>       actual positive index = i + len(x),
>
> where i is the negative index, and len(x) >= abs(i).
>
> e.g.
>
> x = [1,2,3,4,5]
> x[-4] is equivalent to x[-4+len(x)], which is x[1]
> x[-4:-2] is equivalent to x[(-4+len(x)):(-2+len(x))],
> which is x[1:3]
>
> I contend that my restriction may still hold even in
> the case of negative indices, since negative indices
> (which are just convenient shorthand), should map to
> positive indices.
>
> In that case,
> x = [1,2,3]
> x[-10:-9] = [54] should return an exception too since,
>
> x[-10:-9] = x[-10+len(x):-9+len(x)] == x[-7:-6], which
> is REALLY out of bounds of x.

Assignment to x[-4:-3] is not same as assignment to x[-1:0]:

>>> x = [1, 2, 3]
>>> x[-4:-3] = [56]
>>> x
[56, 1, 2, 3]
>>> x = [1, 2, 3]
>>> x[-1:0] = [56]
>>> x
[1, 2, 56, 3]

Although x[-4:-3] and x[-1:0] both evaluate to the same thing (an empty list).  
I would be interested to hear what anyone else has to say about this.

> Instead python will just tack stuff on to the front of
> the array. Which, I still believe, is totally
> inconsistent. But what do I know? I have about 5
> minutes of python experience.
>
> I guess I just don't like that behaviour. At least in
> perl if I assign something to a list slice:
>
> @x[2..3] = (4,5);
>
> the list grows,  so that the things I inserted are at
> the indices where I think I inserted them.
> That is, @x  now contains (0,0,4,5).

That's another way to do it, I suppose. :)

James
-- 
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/





More information about the Python-list mailing list