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]
?
You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed.
The isEmpty () method returns the Boolean value 'true' if this list contains no elements, else it returns false.
Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.
An empty list in Python can be created in two ways, either by using square brackets [] or by using the list() constructor.
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 thanlen(s)
, uselen(s)
. If i is omitted orNone
, use0
. Ifj
is omitted orNone
, uselen(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With