Using word[1:2] instead of just word[1]?

Viewed 74

I came across an example in a Python textbook that used word[1:2] to slice a string. It was doing it this way to demonstrate that only one letter of the string would be sliced.

It got me thinking - is there ever a use case where one would use word[1:2] instead of just word[1], which returns the same result?

3 Answers

The unwritten rule is that slicing will return a sub-sequence and subscription will return an element. It just happens that for length one strings, these notions are equal. But there is a subtle API difference: slicing strings can not throw an IndexError

>>> s = "x"
>>> s[1:2]
''
>>> s[1]
IndexError: string index out of range

In some rare occasions this can be convenient/useful when you want to make a check and avoid the possibility of unhanded exception.

Perhaps also worth mentioning here: there is a more significant difference with bytestrings, for which slicing again returns substrings but subscription returns ordinals.

>>> b'xyz'[1]
121
>>> b'xyz'[1:2]
b'y'

Assuming that you're working with valid indices, for string slicing there's no difference, because a single element of a string is still itself a string (i.e. there's no difference between a "character" and a string that's one character long).

>>> word = 'asdf'
>>> word[1:2]
's'
>>> word[1]
's'

For other slicable objects (e.g. a list) the two may not be equivalent:

>>> word = ['a', 's', 'd', 'f']
>>> word[1:2]
['s']
>>> word[1]
's'

word[1] is different from word[1:2]. word[1] is returning the value of list item with index 1. But also word[1:2] is a list slice which returns the list in the position of 1. example:

word = ['a', 'b', 'c']
print(word[1])
#output: b
#but also
print(word[1:2])
#output: ['b']
Related