Selecting a Portion of a Tuple with Slicing
Just like lists, tuples allow you to extract consecutive elements using slicing
.
To slice a tuple, use square brackets ([]
) with the start index and end index separated by a colon (:
), written as [start_index:end_index]
.
The start index is included in the extraction, whereas the end index is not.
Let's look at an example.
my_tuple = (1, 2, 3, 4, 5, 6) # Slicing from the 2nd to the 4th element slice_tuple = my_tuple[1:4] # Excludes the 5th element, my_tuple[4] # Outputs: (2, 3, 4) print(slice_tuple)
my_tuple[1:4]
slices from the second element (index 1) to the fourth element (index 3).
The fifth element of my_tuple
, my_tuple(4)
, is not included in the extraction through slicing.
Omitting Start or End Index
Omitting the start index slices the tuple from the first element.
Omitting the end index slices the tuple to the last element.
my_tuple = (1, 2, 3, 4, 5, 6) # From the beginning to the third element, my_tuple[2] beginning_slice = my_tuple[:3] # Outputs: (1, 2, 3) print(beginning_slice) # From the fourth element, my_tuple[3], to the end end_slice = my_tuple[3:] # Outputs: (4, 5, 6) print(end_slice)
Using Negative Indices
With negative indices, you can start slicing from the end of the tuple.
# Slicing from the third-to-last element to the end negative_slice = my_tuple[-3:] # Outputs: (4, 5, 6) print(negative_slice)
When slicing a tuple like [start_index:end_index], the end index is not included in the sliced result.
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result