14

Stumbled upon something slightly perplexing today while writing some unittests:

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

Can't for the life of me figure out why blah[:-0] # [] should be the case, the pattern definitely seems to suggest that it should be ['a', 'b', 'c']. Can anybody help to shed some light on why that is the case? Haven't been able to find mention in the docs as to why that is the case.

smci
  • 32,567
  • 20
  • 113
  • 146
Brent Hronik
  • 2,357
  • 1
  • 27
  • 43
  • The - simply means count backwards to find the starting point. Just as `[:-2]` gives a list containing the final 2 elements, `[:-0]` gives a list containing the final 0 elements. – krethika Jun 16 '15 at 22:44
  • 3
    `[:-2]` gives a `list` containing all elements _except_ the last two. – TigerhawkT3 Jun 16 '15 at 22:45

2 Answers2

13

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

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Briefly discussing '-0' is '0', you have to remember that the compiler is evaluating terms as it parses, and so when it sees '-0', it ends up keeping '0'. – bmhkim Jun 16 '15 at 22:43
  • That's the entire thrust of "`-0` is `0`". No need to remember the same thing twice. – TigerhawkT3 Jun 16 '15 at 23:01
8

Python doesn't treat -0 any different from 0.

blah[:0]

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

You can test this by checking that

blah[0:]

is the whole list, starting from the first element.

jwg
  • 5,547
  • 3
  • 43
  • 57