Why isn't slicing out of range?


First of all, please understand that I wrote it using a translator.

I’m using Python version 3.11.1


alpha[7] => out of range

alpha[0:99] => ‘abcdef’

If you look at the above, indexing causes errors when out of range, but slicing does not cause errors when out of index.

I’m teaching students, but I couldn’t find the right answer to this question.

Please guide me and let me know if I am missing anything. Thanks in advance and I look forward to hearing from you.

Best Regards,


1 Like

This behavior is documented here:

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.

As for why it works like this rather than raise IndexError I can only guess. One possible reason could be a desire not to raise errors unnecessarily; an out-of-range slice can safely return a shorter than requested sequence because it is then obvious to the caller that the upper bound was out of range. On the other hand, an out-of-range index could not safely return None, because there would be no way to differentiate between an out-of-range index and an index which actually contains None:

a_list = [None]
b_list = []
# If out-of-range indices were allowed these would be identical:
print(a_list[0], b_list[0])
1 Like

What alpha[0:99] is doing, is to return all the items between index 0 and index 98 (99 being the stop, which is always the last index+1). Because there is no index 98, the stop will simply be the last index+1, in the same way as alpha[0:] will return every index; the stop being len(alpha)+1, which in this example, is 7, or the last index+1.

Slicing will only throw an out of range error if you try and access a none existing index number; as 7 or higher would be in this example.

Maybe my explainer is not “technically correct”, but in essence I don’t think that I’m way off.

1 Like

Hello @Jacob83,

The link to official documentation that @abessman provided offers some good information for your students. Have them look at item 5 in the Notes section. It includes this:

When k is positive, i and j are reduced to len(s) if they are greater.

j is equivalent to the stop value, which is 99 in your example code. Since len('abcdef') is 6, that stop value is reduced to 6 before the slicing process is performed, according to the quoted text. Therefore, there is no attempt to index anything out of range.

Thank you very much to everyone who answered.

I should have read the official document first and asked a question, but I was hasty.
I understand perfectly and I’ll let you know with the contribution of the people who answered in the next class.
Once again, I’d like to thank everyone who answered.

Best Regards,