AppDividend
Latest Code Tutorials

Python Tuple index() Function Example

0

Python tuple index() is an inbuilt method that searched for a given element and returns the index of the element present in the array. If the occurrence of the element is more than one in the tuple, it returns the smallest index of the element.

Python Tuple index()

Python tuple index() method searches an element in a tuple and returns its index. In simple terms, the index() method searches for the given element in a tuple and returns its position. However, if the same item is present more than once, the first/smallest position is returned.

Syntax

tuple.index(element)

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

Return Value

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

Programming Example

# app.py

# 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

In this program, we have declared one tuple containing all weekdays. Then we have printed the tuple. After that, we have found the position on Friday and Monday present in the tuple. As we know, the index of a tuple starts from 0 in Python, so according to the logic, the index of Friday is 5, and Monday is 1.

Let’s see another example.

# app.py

# Python tuple count() Method
# Creating a dictionary
data = (1, 3, 5, 7, 9)  # Tuple of odd numbers
print(data)
# Calling Method
count = data.index(5)
print("Occurences:", count)

Output

python3 app.py
(1, 3, 5, 7, 9)
Occurences: 2

In the above example, it returns 2 because 5 is situated at index 2 because index starts with 0.

Python tuple index() throws Exception

Let’s see an example where value is not there, and we try to find its index.

# app.py

# Python tuple count() Method
# Creating a dictionary
data = (1, 3, 5, 7, 9)  # Tuple of odd numbers
print(data)
# Calling Method
count = data.index(11)
print("Occurences:", count)

Output

pyt python3 app.py
(1, 3, 5, 7, 9)
Traceback (most recent call last):
  File "app.py", line 6, in <module>
    count = data.index(11)
ValueError: tuple.index(x): x not in tuple

Conclusion

The tuple index() method finds a first occurrence of the specified value. The index() function raises an exception if the value is not found.

See also

Python tuple count()

Python dictionary

Python list

Leave A Reply

Your email address will not be published.

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