[Edu-sig] Confusion with slice notation
Trent A. Oliphant
trent at oliphant.org
Mon Jan 5 01:44:36 EST 2004
Here is where I get caught each time with list notation.
(I realized as I was writing this it isn't the slice notation but the index
notation that gets me)
x[:3] returns a list with the first three elements in it.
x[-3:] returns a list with the last three elements in it.
x[2] returns the third element in a list, but
x[-3] returns the third to the last element in a list
To illustrate it another way
x = [1,2,3,4,5,6,7,8,9]
y = [9,8,7,6,5,4,3,2,1]
The way I look at it (and this may be where the problem lies) is that the
[-n] notation is an inverse of sorts of the [n] notation.
Slicing does work that way:
x[:3] = [1,2,3] (3 elements)
y[-3:] = [3,2,1] (3 elements)
However, indexing doesn't
x[3] = 4 (0 based indexing)
y[-3] = 3 (could be viewed as -1 based indexing)
So, I can't take my model for the slices and translate it to indexing, even
though the notation is very similar.
It just seems a bit inconsistent to me, and as I said earlier, I haven't
been able to get it. I am not very good at just memorizing something and
saying that's just the way it is, I need more, and I haven't figured out
what that more is for this issue.
Just some food for thought.
Trent Oliphant
More information about the Edu-sig
mailing list