Tuple slicing in Python is a technique that allows you to extract a portion of a tuple and create a new tuple from it. This is similar to the list slicing technique, but it is applied to tuples. In this article, we will discuss how to perform tuple slicing in Python and how it can be useful.
A tuple is a collection of ordered, immutable values. They are declared using round brackets. Once a tuple is created, its values cannot be modified. This makes tuples ideal for storing data that does not change and for representing items that are logically grouped together.
In Python, we can perform tuple slicing by specifying the start and end indices of the portion we want to extract. The syntax for tuple slicing is similar to that of list slicing i.e. tuple(start:stop:step). Here is an example:
tup = (1, 2, 3, 4, 5) print(tup[1:3])
Output:
(2, 3)
In this example, we have created a tuple t and extracted a portion of it using slicing. The slice starts at index 1 and ends at index 3. This creates a new tuple with values (2, 3).
We can also use negative indices in tuple slicing. Negative indices count from the end of the tuple, so -1 refers to the last item, -2 refers to the second-to-last item, and so on. Here is an example:
tup = (1, 2, 3, 4, 5) print(tup[-3:-1])
Output:
(3, 4)
In this example, we have extracted a portion of the tuple t starting from the third-to-last item and ending at the second-to-last item. This creates a new tuple with values (3, 4).
We can also omit the start or end index when slicing a tuple. If the start index is omitted, it is assumed to be the beginning of the tuple. If the end index is omitted, it is assumed to be the end of the tuple. Here is an example:
tup = (1, 2, 3, 4, 5) print(tup[:3]) print(tup[2:])
Output:
(1, 2, 3) (3, 4, 5)
In this example, we have omitted the start index to extract all values from the beginning of the tuple and omitted the end index to extract all values until the end of the tuple.
In conclusion, tuple slicing is a useful technique in Python that allows you to extract a portion of a tuple and create a new tuple from it. It is similar to the list slicing technique, but it is applied to tuples. By using tuple slicing, we can efficiently manipulate and extract information from tuples.