Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists. You can also use them to modify or delete the items of mutable sequences such as lists. Slices can also be applied on third-party objects like NumPy arrays, as well as Pandas series and data frames.
Slicing enables writing clean, concise, and readable code.
This article shows how to access, modify, and delete items with indices and slices, as well as how to use the built-in class slice().
Let’s create one string, one tuple, and one list to illustrate how to use indices:
>>> str_ = 'Python is awesome!'
>>> str_
'Python is awesome!'
>>> tuple_ = (1, 2, 4, 8, 16, 32, 64, 128)
>>> tuple_
(1, 2, 4, 8, 16, 32, 64, 128)
>>> list_ = [1, 2, 4, 8, 16, 32, 64, 128]
>>> list_
[1, 2, 4, 8, 16, 32, 64, 128]
Indices are provided inside the brackets, that is with the syntax sequence[index]:
>>> str_[0]
'P'
>>> str_[1]
'y'
>>> str_[4]
'o'
>>> tuple_[0]
1
>>> tuple_[1]
2
>>> tuple_[4]
16
>>> list_[0]
1
>>> list_[1]
2
>>> list_[4]
16
The index -1 corresponds to the last item, -2 to the second last, and so on:
>>> str_[-1]
'!'
>>> str_[-2]
'e'
>>> str_[-5]
's'
>>> tuple_[-1]
128
>>> tuple_[-2]
64
>>> tuple_[-5]
8
>>> list_[-1]
128
>>> list_[-2]
64
>>> list_[-5]
8
we can use indices to modify the items of the mutable sequence. In Python, strings and tuples are immutable, but lists are mutable:
>>> list_[-1] = 100
>>> list_
[1, 2, 4, 8, 16, 32, 64, 100]