Why substring slicing index out of range works in Python?



Slicing outside the bounds of a sequence (at least for built-ins) doesn't cause an error. Indexing returns a single item, but slicing returns a subsequence of items. So when you try to index a nonexistent value, there's nothing to return; but when you slice a sequence outside of bounds, you can still return an empty sequence. For example:

>>> s = [1, 2, 3]
>>> s[5:8]
[]

But if you just use an index out of bounds, it'll give you an error:

>>> s = [1, 2, 3]
>>> s[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Advertisements