Hi,
It’s common to remove the first character of a string by typing a[1:] for a string. I was wondering why it also works for a single-character string?
a = 'x'
a[1:]
''
a[1]
Traceback (most recent call last):
File "<input>", line 1, in <module>
IndexError: string index out of range
Evidently, the span of the slice is computed before the actual slicing operation gets completed. Therefore, the str or list is queried based on an expected empty slice, and no elements get requested by the operation.
EDIT (March 10, 2022):
Even this works:
[][100:]
[]
Obviously, there is no element at index 100 there. But there’s no attempt to fetch any elements, and no IndexError is raised.