Frage

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]
War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top