Python Tuple index()

The index() method returns the index of the specified element in the tuple.

Example

# tuple containing vowels
vowels = ('a', 'e', 'i', 'o', 'u')

# index of 'e' in vowels index = vowels.index('e')
print(index) # Output: 1

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 scan
  • start_index (optional) - start scanning the element from the start_index
  • end_index (optional) - stop scanning the element at the end_index

index() Return Value

The index() method returns:

  • the index of the given element in the tuple
  • ValueError exception 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()

# tuple containing vowels
vowels = ('a', 'e', 'i', 'o', 'i', 'u')

# index of 'e' in vowels index = vowels.index('e')
print('Index of e:', index)
# index of the first 'i' is returned index = vowels.index('i')
print('Index of i:', 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

# tuple containing numbers
numbers = (0, 2, 4, 6, 8, 10)

# throws error since 3 is absent in the tuple index = numbers.index(3)
print('Index of 3:', index)

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

# alphabets tuple
alphabets = ('a', 'e', 'i', 'o', 'g', 'l', 'i', 'u')

# returns the index of first 'i' in alphabets
index = alphabets.index('i') 

print('Index of i in alphabets:', index)

# scans 'i' from index 4 to 7 and returns its index index = alphabets.index('i', 4, 7)
print('Index of i in alphabets from index 4 to 7:', index)

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.


Also Read:

Did you find this article helpful?