1

Why does sequence[1:0] return an empty list when sequence[1:] or sequence[1:n] (where n >= sequence length) returns the tail of the list successfully?

I'm pretty sure it's to do with the way that python iterates over the loop, but I can't fathom why it wouldn't work, considering it works for numbers less than zero.

Example:

>>> l = [1,2,3,4]
>>> l[1:]
[2,3,4]
>>> l[1:100]
[2,3,4]
>>> l[1:0]
[]
>>> l[1:0:1]
[]
>>> l[1:-2]
[2]
lightandlight
  • 1,345
  • 3
  • 10
  • 24
  • 2
    Because `0` < `1`; there is nothing between those two indices unless you use a *negative* stride. `l[1:0:-1]` is not empty. – Martijn Pieters Mar 06 '14 at 08:23
  • @MartijnPieters ``-1`` < ``1`` too. Does this have something to do with the negative indices being symbolic? Like python will interpret the index ``-1`` as ``len(sequence) - 1``? – lightandlight Mar 06 '14 at 08:30
  • Negative indices are always subtracted from the length, yes. See the duplicate question. Note that the third slice parameter is not an index, it's the stride. – Martijn Pieters Mar 06 '14 at 08:34
  • Negative indices are a special case made possible by the fact that they can't be normal indices. – RemcoGerlich Mar 06 '14 at 08:38
  • I know how to use slices, this is just an odd case I encountered. The problem seems to be that python will normalise negative indices and indices >= length but it does nothing if the stop index is zero – lightandlight Mar 06 '14 at 08:40

1 Answers1

1

To get the elements backwards, you need to pass the step as a negative value

l = [1,2,3,4]
print l[1:0:-1]
# [2]

When you say l[1:0] Python takes the step value as 1, by default, step is 1.

And when step is greater than 0 and start is greater than or equal to stop, the length of the slice to be returned will be set to 0. So, an empty list will be returned.

if ((*step < 0 && *stop >= *start) || (*step > 0 && *start >= *stop)) {
    *slicelength = 0;
}

When you use negative indices for start or stop, Python adds length of the sequence to it.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497