Definition
A technique used to extract a specific portion (a “slice”) of a sequence, such as a list or string, without modifying the original.
Why It Matters
Slicing is the ‘surgical tool’ of Python; it allows for the high-speed extraction of data subsets without the overhead of explicit loops, making your code cleaner, faster, and more idiomatic.
Core Concepts
- Syntax:
list[start:stop]. Thestartindex is included, but thestopindex is excluded. - Defaults:
[:3]starts at the beginning;[2:]goes to the end. - Negative Slicing:
[-3:]extracts the last three items. - Copying: Using
[:]creates a shallow copy of the entire list, ensuring that changes to the copy do not affect the original.
spam = ['cat', 'bat', 'rat', 'elephant']
# Slicing from index 1 to 3 (3 excluded)
print(spam[1:3]) # ['bat', 'rat']
# Slicing from the beginning
print(spam[:2]) # ['cat', 'bat']
# Slicing to the end
print(spam[1:]) # ['bat', 'rat', 'elephant']