slice
In Python, a slice is an object that allows you to extract a portion of a sequence, such as a list, tuple, or string.
Slices are a powerful way to extract and manipulate parts of sequences. You create a slice by specifying a start, stop, and an optional step index. This enables you to extract a portion of a sequence — either a contiguous range or elements at regular intervals — without the need for looping or extensive indexing.
Syntax
The syntax that lets you get a slice from a sequence is the following:
sequence[start:stop:step]
Example
Here’s an example of how you can use slicing to work with lists:
>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> # Slice from index 2 to 5
>>> subset = numbers[2:6]
>>> subset
[2, 3, 4, 5]
>>> # Slice with a step of 2
>>> step_slice = numbers[0:9:2]
>>> step_slice
[0, 2, 4, 6, 8]
>>> # Slice from index 4 to the end
>>> end_slice = numbers[4:]
>>> end_slice
[4, 5, 6, 7, 8, 9]
>>> # Reverse the list using slicing
>>> reversed_list = numbers[::-1]
>>> reversed_list
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
How Slice Notation Becomes a Slice Object
All three parts of start:stop:step are optional, and any part you leave out arrives as None, which the sequence reads as a sensible default. When Python evaluates the notation, it bundles the three values into a slice object and hands that object to the container’s .__getitem__() method.
The same notation works on the left side of an assignment, which calls .__setitem__(), and after del, which calls .__delitem__(), so you can replace or remove a whole run of items in a mutable sequence.
To watch that translation happen, adjust the three parts below, clear one to leave it out, and switch the operation to see which method receives the slice object:
A class that returns its subscript unchanged makes the object visible:
>>> class Subscript:
... def __getitem__(self, key):
... return key
...
>>> probe = Subscript()
>>> probe[1:5]
slice(1, 5, None)
>>> probe[::2]
slice(None, None, 2)
>>> numbers[1:5:2] == numbers[slice(1, 5, 2)]
True
Related Resources
Tutorial
Reverse Python Lists: Beyond .reverse() and reversed()
In this step-by-step tutorial, you'll learn about Python's tools and techniques to work with lists in reverse order. You'll also learn how to reverse your list by hand.
For additional information on related topics, take a look at the following resources:
- Python's tuple Data Type: A Deep Dive With Examples (Tutorial)
- Lists vs Tuples in Python (Tutorial)
- Exploring Python's tuple Data Type With Examples (Course)
- Python's tuple Data Type: A Deep Dive With Examples (Quiz)
- Lists and Tuples in Python (Course)
- Lists vs Tuples in Python (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.