Summary: in this tutorial, you’ll learn about Python slicing and how to use it to extract data from and assign data to a sequence.
Python slicing review #
So far you’ve learned about slicing such as list slicing.
Technically, slicing relies on indexing. Therefore, slicing only works with sequence types.
For mutable sequence types such as lists, you can use slicing to extract and assign data. For example:
colors = ['red', 'green', 'blue', 'orange']
# extract data
print(colors[1:3])
# assign data
colors[1:3] = ['pink', 'black']
print(colors)Code language: Python (python)Output:
['green', 'blue']
['red', 'pink', 'black', 'orange']Code language: JSON / JSON with Comments (json)However, you can use slicing to extract data from immutable sequences. For example:
topic = 'Python Slicing'
# Extract data
print(topic[0:6])Code language: Python (python)Output:
PythonIf you attempt to use slicing to assign data to an immutable sequence, you’ll get an error. For example:
topic[0:6] = 'Java'Code language: JavaScript (javascript)Error:
TypeError: 'str' object does not support item assignmentCode language: JavaScript (javascript)The slicing seq[start:stop] returns the elements starting at the index start up to the index stop - 1. Therefore, it’s easier to visualize that the indexes are between the elements when you slice the sequence: