logo

Points to Note When Slicing in Python 📂Programing

Points to Note When Slicing in Python

Explanation

When indexing strings, lists, etc. in Python, entering an index that exceeds the last index results in the following error.

>>> list = [0, 1, 2, 3]

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

>>> string = 'abcde'

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

However, when slicing, no error occurs and an empty list is returned. This behavior is the same for Numpy arrays and tensors in Tensorflow or PyTorch.

>>> list[5:7]
[]

>>> string[8:11]
''

I’m not sure why it’s implemented this way or how to apply it, but it’s worth knowing. Otherwise, you might end up wasting a tremendous amount of time chasing bugs like I did.

Environment

  • OS: Windows10
  • Version: Python 3.9.2