Table of Contents
In this post, we will see about Python tuple’s index method.Python tuple’s index method is used to find index of element in the tuple
Python tuple count syntax
1 2 3 |
tuple1.index(element) |
tuple1 is object of the tuple and element is the object which you want to get index.
Python tuple count example
Python tuple index method is used to find index of element.If element is not present in the tuple, then it will raise ValueError.
Let’s understand index method with the example.
1 2 3 4 |
tupleOfCounties=('China','India','USA','Bhutan') print("Index of USA in tupleOfCounties:",tupleOfCounties.index('USA')) |
Output:
If element is not present in the tuple, then it will raise ValueError.
1 2 3 4 |
tupleOfCounties=('China','India','USA','Bhutan') print("Index of Nepal in tupleOfCounties:",tupleOfCounties.index('Nepal')) |
Output:
ValueError Traceback (most recent call last)
1 tupleOfCounties=(‘China’,’India’,’USA’,’Bhutan’)
—-> 2 print(“Index of USA in tupleOfCounties:”,tupleOfCounties.index(‘Nepal’))
3
ValueError: tuple.index(x): x not in tuple
If there are multiple occurrences of element in the list, then index method will return first occurrence.
1 2 3 4 |
tupleOfCounties=('China','India','USA','Bhutan','India') print("Index of India in tupleOfCounties:",tupleOfCounties.index('India')) |
Output:
That’s all about Python tuple index method.