Python Tuple index() Method

Python tuple index() method returns the first occurrence of the given element from the tuple.

Syntax

tuple.index(element)

Parameters

Here, the tuple is the name of the tuple, and the element is the value whose index is to be found.

Return Value

The tuple index() method returns the index/position of the given element. If the element is absent in the tuple, it returns a ValueError.

Example 1: How to Use tuple index() Method

# Declaring a tuple containing all weekdays
weekdays = ('Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat')

# Printing all values of the tuple
print(weekdays)

# Printing index of Friday
pos = weekdays.index('Fri')

print("Position of Friday is: ", pos)

# Printing index of Monday
pos = weekdays.index('Mon')
print("Position of Monday is: ", pos)

Output

('Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat')
Position of Friday is: 5
Position of Monday is: 1

Example 2: Count the occurrences of the element in the tuple

data = (1, 3, 5, 7, 9)
print(data)

count = data.index(5)
print("Occurences:", count)

Output

(1, 3, 5, 7, 9)
Occurences: 2

Example 3: ValueError: tuple.index(x): x not in tuple

data = (1, 3, 5, 7, 9)
print(data)

count = data.index(11)
print("Occurences:", count)

Output

ValueError: tuple.index(x): x not in tuple

Example 4: index() With Start and End Parameters

alphabets = ('d', 'a', 't', 'a', 'f', 'i', 'l', 'l')

index = alphabets.index('t')

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

index = alphabets.index('a', 2, 7)

print('Index of i in alphabets from index 2 to 7:', index)

Output

Index of i in alphabets from index 2 to 7: 3

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.