Python Tutorial Python Advanced Python References Python Libraries

Python - Tuple Slicing



In Python, slicing of a tuple is done to extract part of the tuple. To perform a slicing operation on a tuple, there are two methods which are mentioned below:

Using python slice function

The Python slice() function has one required parameter which is used to specify stop location of slicing. Additionally, it has two optional parameters to specify start location of slicing and step size of slicing.

slice(start, stop, size)
iterable[slice(start, stop, size)]

start Optional. specify the location to start slicing. default is start of the iterable.
stop Required. specify the location to stop slicing.
size Optional. specify the step size of slicing.

In the example below, the slice() function is used on a tuple called MyTuple to slice it in different way. Python supports negative indexing as well which can also be used to slice the tuple.

MyTuple = (0, 1, 2, 3, 4, 5, 6, 7, 9 ,10)

# specifying stop location 
iter_1 = slice(4)
print(MyTuple[iter_1])
iter_2 = slice(-4)
print(MyTuple[iter_2])
print()

# specifying start and stop location 
iter_3 = slice(1,4)
print(MyTuple[iter_3])
iter_4 = slice(-4,-1)
print(MyTuple[iter_4])
print()

# specifying start, stop and step size 
iter_5 = slice(1,8,2)
print(MyTuple[iter_5])
iter_6 = slice(-8,-1,2)
print(MyTuple[iter_6])

The output of the above code will be:

(0, 1, 2, 3)
(0, 1, 2, 3, 4, 5)

(1, 2, 3)
(6, 7, 9)

(1, 3, 5, 7)
(2, 4, 6, 9)

Using index syntax for slicing

Similarly, the index syntax can be used to slice a tuple. The syntax for using this method is given below:

tuple[start:stop:size]

In the example below, the index syntax is used to slice a tuple called MyTuple. The negative indexing can be used here also.

MyTuple = (0, 1, 2, 3, 4, 5, 6, 7, 9 ,10)

# specifying stop location 
print(MyTuple[:4])
print(MyTuple[:-4])
print()

# specifying start location 
print(MyTuple[2:])
print(MyTuple[-4:])
print()

# specifying start and stop location 
print(MyTuple[1:4])
print(MyTuple[-4:-1])
print()

# specifying start, stop and step size 
print(MyTuple[1:8:2])
print(MyTuple[-8:-1:2])

The output of the above code will be:

(0, 1, 2, 3)
(0, 1, 2, 3, 4, 5)

(2, 3, 4, 5, 6, 7, 9, 10)
(6, 7, 9, 10)

(1, 2, 3)
(6, 7, 9)

(1, 3, 5, 7)
(2, 4, 6, 9)

❮ Python - Tuples