This line of code
print [0, 1, 2, 3, 4][0:1:1]
returns [0].
However, the following line of code:
print [0, 1, 2, 3, 4][0:0:1]
returns [].
Why is this? Based on this Explain Python's slice notation, my understanding is that the format should be:
a[start:end:step] # start through not past end, by step
So shouldn't [0, 1, 2, 3, 4][0:0:1] start and end at the 0th value, thus returning [0]?
3 Answers 3
The "end" index of a slice is always excluded from the result; i.e., listy[start:end] returns all listy[i] where start <= i < end (note use of < instead of <=). As there is no number i such that 0 <= i < 0, listy[0:0:anything] will always be an empty list (or error).
Comments
The end index in Python's slice notation is exclusive. A slice of [n:m] will return every element whose index is>= n and < m.
To simplify things a bit, try it without the step (which isn't necessary when the step value is 1):
>>> a = [0, 1, 2, 3, 4]
>>> a[0:1]
[0]
>>> a[0:0]
[]
As a general rule, the number of elements in a slice is equal to the slice's start index minus the slice's end index. I.e., the slice [n:m] will return m-n elements. This agrees with the one element (1-0) returned by [0:1] and zero elements (0-0) returned by [0:0].
(Note that this is not true if either of the slice indices is outside of the size of the array.)
For a nice visualization of how slice indices work, search for "One way to remember how slices work" at http://docs.python.org/2/tutorial/introduction.html
Comments
Note that is [0:0:1] not [0:1:1]
So:
start = 0
end = 0
step = 1
The slice [start:end:step] means it will return values that are between start and end - 1 with a certain step, so for your example:
...[0:0:1]
Values between 0 and -1, so it doesn't return anything.
not past endis incorrect -up to (but not including) endis correct. Python slices are inclusive at thestartend but exclusive at theendend.