Remove the first character from a string

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'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: string index out of range


1 Like

It also works for a list.


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:


Obviously, there is no element at index 100 there. But there’s no attempt to fetch any elements, and no IndexError is raised.

1 Like

Subscripting with an index requires that index to actually exist.

Slicing is more tolerant.

This is described in the docs:

See the comment:

Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j.

So if both i and j are out of range, there are no items to be selected and an empty sequence (list, string, tuple etc) is returned.