Assignment to slice

r.e.s. r.s at ZZmindspring.com
Wed Jan 21 23:54:43 EST 2004


"James Henderson" <james at logicalprogression.net> wrote ...

JH  Assignment to x[-4:-3] is not same as assignment to x[-1:0]:
JH
JH   >>> x = [1, 2, 3]
JH   >>> x[-4:-3] = [56]
JH   >>> x
JH   [56, 1, 2, 3]
JH   >>> x = [1, 2, 3]
JH   >>> x[-1:0] = [56]
JH   >>> x
JH   [1, 2, 56, 3]
JH
JH   Although x[-4:-3] and x[-1:0] both evaluate to the same 
JH   thing (an empty list).  
JH   I would be interested to hear what anyone else has to say 
JH   about this.

Here's my beginner's take on "slice indices" ... 

Since len(x)==3, *only* the values -1, -2, and -3 are shorthand, 
standing for 2, 1, 0 resp.;  i.e., only -1, -2, ..., -len(x) are
shorthand, and any other negative integer is equivalent to 0;
any positive integer values > len(x) are equivalent to len(x).

So, x[-4:-3] stands for x[0:0], while x[-1:0] stands for x[2:0].
Both x[0:0] and x[2:0] are empty lists, but x[0:0] is located 
"just before x[0]" whereas x[2:0] is located ""just before x[2]",
and the assignments amount to insertions at the resp. locations. 

I trust someone will correct me if I'm wrong, but it seems to me 
a simpler restatement of what's in the Python Reference Manual.

--r.e.s.



More information about the Python-list mailing list