Python tuple index()

Previous
Next

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

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.

tupleOfCounties=('China','India','USA','Bhutan') print("Index of USA in tupleOfCounties:",tupleOfCounties.index('USA'))

Output:

Index of USA in tupleOfCounties: 2

If element is not present in the tuple, then it will raise ValueError.

tupleOfCounties=('China','India','USA','Bhutan') print("Index of Nepal in tupleOfCounties:",tupleOfCounties.index('Nepal'))

Output:

—————————————————————————
ValueError Traceback (most recent call last)
in ()
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.

tupleOfCounties=('China','India','USA','Bhutan','India') print("Index of India in tupleOfCounties:",tupleOfCounties.index('India'))

Output:

Index of India in tupleOfCounties: 1

That’s all about Python tuple index method.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog