0

I always thought that omitting arguments in the python slice operation would result into:

  • start = 0
  • end = len(lst)
  • step = 1

That holds true if the step is positive, but as soon as the step is negative, like in the "reverse slice" [::-1], omitting start/end results in:

  • start = len(lst)-1
  • end = None

Is this a special case, or am I missing something?

1 Answer 1

2

The default is always None; it is up to the type to determine how to handle None for any of the 3 values. The list object is simply passed a slice(None, None, -1) object in this case.

See footnote 5 to the operations table in the sequence types documentation for how Python's default sequence types (including list objects) interpret these:

s[i:j:k]
5. [...] If i or j are omitted or None, they become “end” values (which end depends on the sign of k).

So the defaults are dependent on the sign of the step value; if negative the ends are reversed. For [::-1] the end values are len(s) - 1 and -1 (absolute, not relative to the end), respectively, because the step is negative.

Sign up to request clarification or add additional context in comments.

5 Comments

Why do you say -1 and not None for j?
@wim: yes, because the end value is not included in the slice. If you set it to 0 you won't get that first element.
@wim: note that if you used s[len(s) - 1:-1:-1] the value for j is taken relative to the length and it won't work; only None or leaving it empty would let you include the first element.
I see what you mean. It's a bit confusing, because we never use -1 to mean that in a slice
I only read the "What's new in Python 2.3" article that introduced the extended slice syntax. Thank you for a better reference!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.