Sitelet https://java2blog.com/python-tuple-index/

Python tuple index()

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.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.

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.