Computer >> Computer tutorials >  >> Programming >> Python

How to index and slice a tuple in Python?


To index or slice a tuple you need to use the [] operator on the tuple. When indexing a tuple, if you provide a positive integer, it fetches that index from the tuple counting from the left. In case of a negative index, it fetches that index from the tuple counting from the right. 

example

my_tuple = ('a', 'b', 'c', 'd')
print(my_tuple[1])
print(my_tuple[-1])

Output

This will give the output −

b
d

If you want to get a part of the tuple, use the slicing operator. [start:stop:step]. 

example

my_tuple = ('a', 'b', 'c', 'd')
print(my_tuple[1:]) #Print elements from index 1 to end
print(my_tuple[:2]) #Print elements from start to index 2
print(my_tuple[1:3]) #Print elements from index 1 to index 3
print(my_tuple[::2]) #Print elements from start to end using step sizes of 2

Output

This will give the output −

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