I'm new to Python, the following output I'm getting from a simple list slice operation confused the jebuse out of me.
Here is the code.
>>> a = [1,2,3,4];
>>> a[1:3]
[2, 3]
>>> a[3]
4
shouldn't a[1:3] returns [2,3,4] instead of [2,3]?
a[1:3] specifies a half-closed interval, which means it includes the values starting at the 1st specified index up to, but not including, at the 2nd index.
So in this case a[1:3] means the slice includes a[1] and a[2], but not a[3]
You see the same in the use of the range() function. For instance
range(1, 5)
will generate a list from 1 to 4, but will not include 5.
This is pretty consistent with how things are done in many programming languages.
[1, 5) to mean 1, 2, 3, 4, whereas [1, 5] is 1, 2, 3, 4, 5 (if I remember my math notation correctly .. it's been a while :) .. see also this: mathworld.wolfram.com/Half-ClosedInterval.htmlThe docs for slice may help.
slice([start], stop[, step])
Return a slice object representing the set of indices specified byrange(start, stop, step).
The slice format that most of are familiar with is just a shorthand:
a[start:stop:step]