Why slicing a python list does not infer an index from a related error?

While playing with array partitioning, I noticed that the slice type a[index:] or a[:index] does not derive the index of the array from the associated error for strings.

 str = "abcde" print str[10:] print str[:10] 

outputs the result:

 '' abcde 

Can someone explain why? Should it throw an array index error outside the bounds? Python creates this error if I try to do something like: print str[10] .

+8
python string list slice
source share
2 answers

Slicing is used to create a new list. If the indices do not fall within the range of the number of elements in the list, we can return an empty list. Thus, we do not need to throw an error.

But if we try to access elements in a list that is larger than the number of elements, we cannot return the default value (not even None , because it may be a valid value in the list). That's why

 IndexError: list index out of range 

.

When slicing, if the initial index is greater than or equal to the length of the sequence, the length of the returned sequence is set to 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 strings, if the length of the string to be returned after cutting is 0, then it returns an empty string in that string

 if (slicelength <= 0) { return PyString_FromStringAndSize("", 0); } 
+11
source share

The way the slicing operator is implemented in python. If the array indices are outside the bounds, it will automatically truncate to the right place.

+1
source share

All Articles