How to Slice a Tuple in Python?

Python – Slice a Tuple

To slice a Tuple in Python, use slice() builtin function.

slice() builtin function returns a slice object. And we can use this slice object to slice a Python Tuple. All we need to do is, pass the slice object as an index in the square brackets after the tuple variable. This expression returns the sliced tuple.

The following is a sample code snippet to slice a tuple object with specific value for stop parameter in slice function.

tuple_object = ()
slice_object = slice(stop)
result = tuple_object[slice_object]

The following is a sample code snippet to slice a tuple object with specific value for start, stop and an optional step parameter in slice function.

tuple_object = ()
slice_object = slice(start, stop[, step])
result = tuple_object[slice_object]

Example 1: Slice Tuple with Specific End Position

In this example, we will prepare a slice object with specific end/stop position stop=5, and use this slice object to slice given tuple.

Python Program

tuple_1 = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
stop = 4 #end position of slice
slice_object = slice(stop)
result = tuple_1[slice_object]
print(result)
Run

Output

('a', 'b', 'c', 'd')

The slice object would contain the indices [0, 1, 2, 3] for given stop value of 4. And the elements in the tuple corresponding to these indices will be returned by tuple_1[slice_object]. Hence the resulting tuple ('a', 'b', 'c', 'd').

Example 2: Slice Tuple with Specific Start and End Positions

In this example, we will prepare a slice object with specific start and stop positions, and use this slice object to slice given tuple.

Python Program

tuple_1 = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
start = 2 #start position of slice
stop = 7 #end position of slice
slice_object = slice(start, stop)
result = tuple_1[slice_object]
print(result)
Run

Output

('c', 'd', 'e', 'f', 'g')

The slice object would contain the indices [2, 3, 4, 5, 6] for given start and stop values. And the elements in the tuple corresponding to these indices are returned by tuple_1[slice_object]. Hence the resulting tuple ('c', 'd', 'e', 'f', 'g').

Example 3: Slice Tuple with Specific Start and End Positions, Step

In this example, we will prepare a slice object with specific start and stop positions, and also a specific value for step. We shall then use this slice object to slice given tuple.

Python Program

tuple_1 = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
start = 2 #start position of slice
stop = 7 #end position of slice
step = 2
slice_object = slice(start, stop, step)
result = tuple_1[slice_object]
print(result)
Run

Output

('c', 'e', 'g')

The slice object would contain the indices [2, 4, 6]. And the elements in the tuple corresponding to these indices shall be returned by tuple_1[slice_object]. Hence the resulting tuple ('c', 'e', 'g').

Summary

In this tutorial of Python Examples, we learned how to slice a tuple, using slice() builtin function.