Slice a Tuple

To slice a Tuple in Python, use slice() builtin function. We can just provide stop position for slicing a tuple; or provide both start and stop positions to slice() function.

slice() function returns indices. We use these indices along with the original tuple, to create the resulting sliced tuple.

Python slice() builtin function

Examples

ADVERTISEMENT

1. Slice a Tuple with Stop Position

In the following program, we take a tuple x with integer values, and slice this tuple until stop=4.

Python Program

aTuple = (2, 5, 8, 1, 9, 3, 7, 4)
stop = 4
indices = slice(stop)
result = aTuple[indices]
print('Sliced Tuple :', result)
Try Online

Output

Sliced Tuple : (2, 5, 8, 1)

2. Slice a Tuple with Start and Stop

We can specify both start and stop positions to slice() function, to slice a tuple from a specific starting position until specific stop position.

Python Program

aTuple = (2, 5, 8, 1, 9, 3, 7, 4)
start = 2
stop = 5
indices = slice(start, stop)
result = aTuple[indices]
print('Sliced Tuple :', result)
Try Online

Output

Sliced Tuple : (8, 1, 9)

3. Slice a Tuple with Steps

Along with start and stop positions, we could also specify step value to slice() function. Indices from given start are taken in steps until specified stop.

Python Program

aTuple = (2, 5, 8, 1, 9, 3, 7, 4, 2, 4, 3)
start = 2
stop = 8
step = 3
indices = slice(start, stop, step)
result = aTuple[indices]
print('Sliced Tuple :', result)
Try Online

Output

Sliced Tuple : (8, 3)

Conclusion

In this Python Tutorial, we learned how to slice a Tuple in Python using slice() function.