Learn how to slice tuples in Python with step-by-step examples. Master tuple indexing, slicing syntax (start:stop:step), and immutable operations for efficient coding.
Tuple slicing is a technique to extract a portion (subset) of a tuple by specifying start, stop, and step indices.
sub_tuple = original_tuple[start:stop:step]
start is included, stop is excludedstart=0, stop=len(tuple), step=1my_tuple = (10, 20, 30, 40, 50, 60)
print(my_tuple[1:4]) # (20, 30, 40) - from index 1 to 3
print(my_tuple[:3]) # (10, 20, 30) - from start to index 2
print(my_tuple[2:]) # (30, 40, 50, 60) - from index 2 to end
print(my_tuple[:]) # (10, 20, 30, 40, 50, 60) - full copy
print(my_tuple[-3:]) # (40, 50, 60) - last 3 elements
print(my_tuple[:-2]) # (10, 20, 30, 40) - all except last 2
print(my_tuple[::2]) # (10, 30, 50) - every 2nd element
print(my_tuple[1:5:2]) # (20, 40) - from index 1 to 4, step 2
print(my_tuple[::-1]) # (60, 50, 40, 30, 20, 10) - reversed tuple
t = (1, 2, 3)
print(t[1:100]) # (2, 3) → No error, returns available elements
Direct indexing with out-of-range indices → IndexError
Example:
t = (1, 2, 3)
print(t[5]) # IndexError: tuple index out of range
Here are some tuple slicing tasks for students to practice and reinforce their understanding:
t = (5, 10, 15, 20, 25, 30, 35, 40), extract:
(5, 10, 15)(15, 20, 25, 30)(25, 30, 35, 40)(5, 15, 25, 35)colors = ('red', 'green', 'blue', 'yellow', 'black', 'white'), extract:
('red', 'white')('blue', 'yellow')('white', 'black', 'yellow', 'blue', 'green', 'red')nums = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), extract:
(8, 9, 10)(1, 2, 3, 4, 5, 6, 7, 8)(6, 7, 8)letters = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'), extract:
('a', 'd', 'g', 'j')('b', 'd', 'f', 'h')('j', 'h', 'f', 'd', 'b')Tutorials, Roadmaps, Bootcamps & Visualization Projects