simple beginner question about lists and negative index
Terry Reedy
tjreedy at udel.edu
Thu May 1 13:04:50 EDT 2008
"jmDesktop" <needin4mation at gmail.com> wrote in message
news:c7424798-5b2c-4a72-8cfb-023ac067db71 at w7g2000hsa.googlegroups.com...
| This program:
|
| s = 'abcde'
| i = -1
| for i in range (-1, -len(s), -1):
| print s[:i], i
|
| gives
|
| abcd -1
| abc -2
| ab -3
| a -4
|
| Why doesn't the first one have the e if -1 is the end of the list? In
| Dive Into Python it said that -1 was the end of the list. Thanks.
A sequence with n items has n+1 slice positions, numbered 0 to n: the 2 at
beginning and end and n-1 between items. Example
-a-b-c-
0 1 2 3
has 4 slice positions.
Hence the first item is seq[0:1] and last is seq[n-1:n]
In a sense, we 'ought' to index sequences with average of two successive
slice positions, giving seq[1/2],,,seq[n-1/2].
But this is inconvenient, so we either round down (C, Python, etc) or up
(Fortran), giving seq[0],,,,seq[n-1] or seq[1],,,seq[n].
Python allows n-1 and n-k to be abbreviated as -1 and -k.
-1 as an abbreviation of n-1 is only the end of the list for indexing.
n is the end for slicing. It is abbreviated by omission. Perhaps
for i in range(n+1): print i, 'abcde'[:5-i]
will make this all even clearer.
Terry Jan Reedy
More information about the Python-list
mailing list