Why python’s list slicing doesn’t produce index out of bound error? [duplicate]

Why python’s list slicing doesn’t produce index out of bound error? [duplicate]

This question already has answers here:

Why does substring slicing with index out of range work?

                                    (3 answers)

Closed 5 years ago.

While playing with array slicing I noticed that a[index:] or a[:index] type of slicing doesn't produce array index out of bound error for strings.
str = "abcde"
print str[10:]
print str[:10]

produces output :

Can anybody explain why? Shouldn't it produce array index out of bounds error ? Python does produce this error if I try to do something like : print str[10].


Answer 1:

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 why

IndexError: 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 line

defstop = *step < 0 ? -1 : length;
if (r->stop == Py_None) {
    *stop = defstop;
if ((*step < 0 && *stop >= *start)
    || (*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 line

if (slicelength <= 0) {
    return PyString_FromStringAndSize("", 0);

Answer 2:

That’s how the slicing operator is implemented in python. If the array indices are out of bounds, it will automatically truncate then at the right places.