The index() method returns the index of the specified element in the tuple.
Example
index() Syntax
The syntax of the index() method is:
tuple.index(element, start_index, end_index)
Here, the index() scans the element in the tuple from start_index to end_index.
index() Parameter
The index() method can take one to three parameters:
element- the item to scanstart_index(optional) - start scanning theelementfrom thestart_indexend_index(optional) - stop scanning theelementat theend_index
index() Return Value
The index() method returns:
- the index of the given element in the tuple
ValueErrorexception if the element is not found in the tuple
Note: The index() method only returns the first occurrence of the matching element.
Example 1: Python Tuple index()
Output
Index of e: 1 Index of i: 2
In the above example, we have used the index() method to find the index of a specified element in the vowels tuple.
The element 'e' appears in index 1 in the vowels tuple. Hence, the method returns 1.
The element 'i' appears twice in the vowels tuple. In this case, the index of the first 'i' (which is 2) is returned.
Example 2: index() throws an error if the specified element is absent in the Tuple
Output
ValueError: tuple.index(x): x not in tuple
In the above example, we have used the index() method to find the index of an element that is not present in the numbers tuple.
Here, numbers doesn't contain the number 3. Hence, it throws an exception
Example 3: index() With Start and End Parameters
Output
Index of i in alphabets: 2 Index of i in alphabets from index 4 to 7: 6
In the above example, we have used the index() method to find the index of the element 'i' with the start and end parameters.
Here, 'i' is scanned from index 4 to index 7 in the tuple alphabets. Once found, the index of the scanned 'i' is returned.