Tuple Slicing In Python

Tuple Slicing In Python

We are now familiar with the thing, that to access the individual tuple elements, we need to use the indexes. Using these indexes, we can access the individual items. But the thing is, if we are required to access a range of tuple elements, we can do so, using the slicing operator. This is similar to list slicing, or string slicing, where we need to specify the start, stop and step as well. Now, Let’s have a quick look at an example, which demonstrates tuple slicing, to access a range of items in a tuple.

As you can see, in the above program, we have a simple tuple, and then we are trying to access a range of elements in the tuple.

Tuple Slicing In Python

Here, we have specified the start as 1, and the stop as 4. So, we get the first element as the index 1 element, and the last element as the index 3 element, since the stop itself is excluded. So, you can get a range of tuple items using slicing.
Also, we can have the step here, which simply means how many steps after accessing some element. Have a look at the below program, which tries to demonstrate the step here.

As you can see in the above program, we have a simple tuple, and then we are trying to access a range of tuples. We have omitted the start, and the stop, so here, we are going to go from the start to end, and here, we have provided step 2, which we can simply understand as if after accessing the first element, it accesses the 3rd element, moving two steps forward.

If we want to reverse our tuple, we can do it easily with tuple slicing. We just have to omit the start and stop values here, and then we have to provide the step value as -1. Let’s give it a try now.

As you can see in the above program, we have a simple tuple, and then we are trying to reverse the tuple. Simply, we have omitted the start and the stop, and then we have provided the step as -1, and when we look at the output, we can find that we get a reversed tuple. Note that in this case, the original tuple is not being modified.

So, with tuple slicing, we can access a number of elements from the tuple. So, whenever we need to access a range of elements in our tuple, we can perform tuple slicing.