Python Tuple index() Method
Python Tuple index() Method
The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if the value is not found.
Syntax
tuple.index(value)
Parameter
value- This parameter represents the element to search in the tuple
Return
This method returns the position/index for the specified element in the tuple or returns a ValueError exception if the value is not found.
Example 1
# Python program explaining # the tuple.index() method # initializing the tuple values tupleVal = (1, 2, 3,4,5, 7, 8, 7, 5, 5, 6, 4, 4) print("Tuple:",tupleVal) # finds the first occurrence of the specified value and returns its index Index = tupleVal.index(4) # printing the returned value print("The index value of '4' is",Index)
Output
Tuple: (1, 2, 3, 4, 5, 7, 8, 7, 5, 5, 6, 4, 4) The index value of '4' is 3
Example 2
# Python program explaining # the tuple.index() method # initializing the alphabetic tuple values vowels = ('a','f','l', 'm', 'u') #passing an element that is not present in the tuple # element 'p' is searched index = vowels.index('r') # will return an ValueError exception print('The index of r:', index)
Output
Traceback (most recent call last): File "main.py", line 9, in <module> index = vowels.index('r') ValueError: tuple.index(x): x not in tuple