[Tutor] dicey slices

peter hodgson py at gogol.humnet.ucla.edu
Mon Apr 19 11:07:49 EDT 2004


Hi. Thanks for being here. I'm weighing in on an earlier discussion
about indexing.

## here's what a tutorial says:

SLICES and indeces:

The best way to remember how slices work is to think of the indices as
pointing between characters, with the left edge of the first character
numbered 0. Then the right edge of the last character of a string of n
characters has index n, for example:

 +---+---+---+---+---+ 
 | H | e | l | p | A |
 +---+---+---+---+---+ 
 0   1   2   3   4   5 
- - -5  -4  -3  -2  -1

## here's what i infer; does it compute? thanks again; peter

i.e: each char's index takes the number of the LEFT side of the space
occupied by the character, ASCENDING [n] or DESCENDING [-n]

 / 1 / 2 / 3 / 4 / 5 /
 0   1   2   3   4   5
- - -5  -4  -3  -2  -1

>>> s = '12345'
>>> s[1]
'2'
>>> s[-1]
'5'

NB: index and slice "read" differently:

 s[n] names the char in the n+1th space, ascending
>>> s[1], s[2], s[3]
('2', '3', '4')
BUT:
>>> s[1:3]
'23'
so we must type
>>> s[1:4]
'234'

 s[-n] names the char in the nth space, descending,

>>> s[-4], s[-3], s[-2]
('2', '3', '4')
BUT:
>>> s[-4:-2]
'23'
so we must type
>>> s[-4:-1]
'234'

thus, also
>>> s[1:-1]
'234'
>>> s[-4:4]
'234'

so, for slices, 
 s[X:X+n] yields a segment starting with the char in the (X+1)th space,
but no including the char in the (X+n)th space;

>>> t[2:4]
'34'
>>> t[2:6]
'3456'

TWO COUNTERINTUITIVE FEATURES EMERGE:
 1/ negative indeces yield the [-]numbered char space;
 2/ right-hand slice limits exclude the actual indexed char space;

these features are manifest thus:

 a slice [X:-n] grabs UP TO the char which is n spaces from the
end;
 but the slice [X:n] grabs UP TO  the char which is n+1 spaces from the
beginning;

which yields the corollary:

 if len(s) == i: 
 and 
 if i % 2 == 1 
 then s[n] !== s[-n] 
 [i.e., in a string with an odd number of items, char #n will never be
the same as char #-n]

>>> s[3], s[-3]
('4', '3')
>>> t = '123456'
>>> t[3], t[-3]
('4', '4')








More information about the Tutor mailing list