What are the default slice indices *really*?

Solution 1:

There actually aren't any defaults; omitted values are treated specially.

However, in every case, omitted values happen to be treated in exactly the same way as None. This means that, unless you're hacking the interpreter (or using the parser, ast, etc. modules), you can just pretend that the defaults are None (as recursive's answer says), and you'll always get the right answers.

The informal documentation cited isn't quite accurate—which is reasonable for something that's meant to be part of a tutorial. For the real answers, you have to turn to the reference documentation.

For 2.7.3, Sequence Types describes slicing in notes 3, 4, and 5.

For [i:j]:

… If i is omitted or None, use 0. If j is omitted or None, use len(s).

And for [i:j:k]:

If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

For 3.3, Sequence Types has the exact same wording as 2.7.3.

Solution 2:

The end value is always exclusive, thus the 0 end value means include index 1 but not 0. Use None instead (since negative numbers have a different meaning):

>>> s[len(s)-1:None:-1]
'gnirtsym'

Note the start value as well; the last character index is at len(s) - 1; you may as well spell that as -1 (as negative numbers are interpreted relative to the length):

>>> s[-1:None:-1]
'gnirtsym'

Solution 3:

I don't have any documentation, but I think the default is [None:None:None]

>>> "asdf"[None:None:None]
'asdf'
>>> "asdf"[None:None:-1]
'fdsa'

Solution 4:

The notes in the reference documentation for sequence types explains this in some detail:

(5.) The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

So you can get the following behaviour:

>>> s = "mystring"
>>> s[2:None:-1]
'sym'

Solution 5:

Actually it is logical ...

if you look to the end value, it always points to the index after the last index. So, using 0 as the end value, means it gets till element at index 1. So, you need to omit that value .. so that it returns the string you want.

>>> s = '0123456789'
>>> s[0], s[:0]
('0', '')
>>> s[1], s[:1]
('1', '0')
>>> s[2], s[:2]
('2', '01')
>>> s[3], s[:3]
('3', '012')
>>> s[0], s[:0:-1]
('0', '987654321')