2

I just wonder why slice [::-1] is the same as [-1::-1]?

Syntax for reference: [start:stop:step]

It's interesting because almost every Internet article about Python slices states that start defaults to 0. But it seems start defaults to -1 when a step is a negative number. I didn't find that information in the official Python Docs. Could someone clarify this?

Example:

lst = ['c', 'a', 't']
print(lst[0::-1])
print(lst[::-1])
print(lst[-1::-1])

Output:

['c']
['t', 'a', 'c']
['t', 'a', 'c']
filler36
  • 456
  • 7
  • 13
  • 3
    According to official Python docs, start and stop arguments of slice default to `None`. – matszwecja Jul 01 '22 at 10:43
  • 1
    The effective defaults change when the `step` is negative. It's easier to think of them, not as specific numbers, but as logical end points. When `step` is positive, it starts at the beginning and runs until the end. When `step` is negative, it starts at the end and runs until the beginning. `-1` is equivalent to the last element, so as a start point with negative `step`, it's equivalent to not passing the `start` index, the same way that passing `0` is equivalent to not passing the `start` index for a positive `step`. (I say equivalent, but to be clear, omitted values are *actually* `None`) – ShadowRanger Jul 01 '22 at 10:46
  • 2
    "When `k` is negative, `i` and `j` are reduced to `len(s) - 1` if they are greater. If `i` or `j` are omitted or `None`, they become “end” values (which end depends on the sign of `k`)" — [docs](https://docs.python.org/3/library/stdtypes.html#typesseq:~:text=If%20i%20or%20j%20are%20omitted%20or%20None%2C%20they%20become%20%E2%80%9Cend%E2%80%9D%20values%20(which%20end%20depends%20on%20the%20sign%20of%20k).) on `s[i:j:k]` – Amadan Jul 01 '22 at 10:47

0 Answers0