Remove the first character from a string

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

Moreover,

a[2:]
''
a[:-1]
''
a[:-2]
''
1 Like

It also works for a list.

[][1:]
[]

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.

1 Like

Subscripting with an index requires that index to actually exist.

Slicing is more tolerant.

This is described in the docs:

https://docs.python.org/3/reference/datamodel.html#types

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.

2 Likes