Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - Understanding negative steps in list slicing

I am trying to understand the following behavior and would welcome any references (especially to official docs) or comments.

Let's consider a list:

>>> x = [1,2,3,4,5,6]

This works as expected

>>> x[-1:-4:-1] 
[6, 5, 4]

But I am surprised the following is empty:

>>>  x[0:-4:-1] 
[]

Consequently, I am surprised the following is not empty

>>> x[0:-len(x)-1:-1]
> [1]

especially given that

>>> x[0:-len(x):-1] 
[]

and also that

>>> x[0:-len(x)-1] 
[]

is empty.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...