展开全部
这里有详细的回答。
Slicing is used to create a new list. If the indices don't fall within the range of the number of elements in the list, we can return an empty list. So, we don't have to throw an error.
But, if we try to access the elements in the list which is greater than the number of elements, we cannot return any default value (not even None because it could be a valid value in the list). That is whyIndexError: list index out of range
is thrown.
While slicing, if the starting index is greater than or equal to the length of the sequence, the length of the returned sequence is set to be 0, in this linedefstop = *step
...
if (r->stop == Py_None) {
*stop = defstop;
}
...
if ((*step = *start)
||e68a84e8a2ad3231313335323631343130323136353331333335343430 (*step > 0 && *start >= *stop)) {
*slicelength = 0;
For the Strings, if the length of the string to be returned after slicing is 0, then it returns an empty string, in this lineif (slicelength <= 0) {
return PyString_FromStringAndSize("", 0);
}