The fact that
> x[-1:-4:-1]
[6, 5, 4]
> x[0:-4:-1]
[]
should not surprise you! It is fairly obvious that you can slice a list from the last to the fourth-last element in backwards steps, but not from the first element.
In
x[0:i:-1]
the i
must be < -len(x)
in order to resolve to an index < 0
for the result to contain an element.
The syntax of slice is simple that way:
x[start:end:step]
means, the slice starts at start
(here: 0
) and ends before end
(or the index referenced by any negative end
). -len(x)
resolves to 0
, ergo a slice starting at 0
and ending at 0
is of length 0
, contains no elements. -len(x)-1
, however, will resolve to the actual -1
, resulting in a slice of length 1
starting at 0
.
Leaving end
empty in a backward slice is more intuitively understood:
> l[2::-1]
[3, 2, 1]
> l[0::-1]
[1]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…