Home ยป Slice a Tuple in python

Slice a Tuple in python

In this example we show how you can slice a tuple in python

Syntax:

slice(stop)
slice(start, stop, step)

Parameters:

start: (Optional) Starting index where the slicing of the iterable starts. Deault is none.
stop: Ending index where the slicing should end.
step: (Optional) An integer to increment starting index. Default is none.

Example

 

number_tuple = (10, 20, 30, 40, 50, 60, 70, 80, 90)

print("Tuple Items = ", number_tuple)

slice1 = number_tuple[1:6]
print("Tuple Items = ", slice1)

slice2 = number_tuple[4:]
print("Tuple Items = ", slice2)

slice3 = number_tuple[:5]
print("Tuple Items = ", slice3)

slice4 = number_tuple[:]
print("Tuple Items = ", slice4)

slice5 = number_tuple[-5:-2]
print("Tuple Items = ", slice5)

slice6 = number_tuple[-4:]
print("Tuple Items = ", slice6)

slice7 = number_tuple[:-4]
print("Tuple Items = ", slice7)

slice8 = number_tuple[1:7:2]
print("Tuple Items = ", slice8)

When you run this you will see something like this

>>> %Run slicetuple.py
Tuple Items =  (10, 20, 30, 40, 50, 60, 70, 80, 90)
Tuple Items =  (20, 30, 40, 50, 60)
Tuple Items =  (50, 60, 70, 80, 90)
Tuple Items =  (10, 20, 30, 40, 50)
Tuple Items =  (10, 20, 30, 40, 50, 60, 70, 80, 90)
Tuple Items =  (50, 60, 70)
Tuple Items =  (60, 70, 80, 90)
Tuple Items =  (10, 20, 30, 40, 50)
Tuple Items =  (20, 40, 60)

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More