Is list[i:j] guaranteed to be an empty list if list[j] precedes list[i]?

Question:

The Python tutorial explains slice behavior when indices are negative, but I can’t find documentation describing the behavior when the end index precedes the start index. (I’ve also looked at Explain Python’s slice notation, and perhaps I’m not reading carefully enough, but the answers there don’t seem to address this point.)

The behavior that I observe is that an empty list is returned, which seems reasonable to me. However, it also would seem reasonable to me for this to return a list of items between i and j in reversed order or to simply raise an exception.

Is list[i:j] guaranteed to be an empty list if list[j] precedes list[i]?

Asked By: jamesdlin

||

Answers:

Yes, if j <= i is true, the resulting slice is empty, for standard Python types. To get the results in reverse order, you need to add a negative stride:

list[i:j:-1]

because explicit is better than implicit.

This is documented in Common Sequence Operations, footnote 4:

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

Bold emphasis mine.

Custom types are free to interpret this differently.

Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.