Why slice [: -0] returns an empty list in Python

I came across something a little puzzled today when I wrote several unittests:

blah = ['a', 'b', 'c'] blah[:-3] # [] blah[:-2] # ['a'] blah[:-1] # ['a', 'b'] blah[:-0] # [] 

It is impossible for my life to determine why blah[:-0] # [] should be like this, the template definitely seems to be ['a', 'b', 'c'] . Can anyone help shed some light on why this is so? It was not possible to find in the documents a mention of why this is so.

+5
source share
2 answers

-0 is 0 , and the slice that goes from the beginning of list inclusive to index 0 not inclusive is an empty list .

+11
source

Python does not refer to -0 other than 0 .

 blah[:0] 

means all elements, but not including the first. This is an empty list, and blah[:-0] is the same.

You can verify this by setting that

 blah[0:] 

- This is the entire list, starting with the first item.

+5
source

All Articles