Tuples in Python are immutable data structures used to store data in a sequential manner. In this article, we will discuss the tuple index() method in Python. We will also discuss how to get the index of an element in a tuple in Python.
The Tuple index() Method in Python
The index()
method is used to find the index of an element in a tuple in Python. When invoked on a tuple, the index()
method takes a value as its input argument. After execution, it returns the index of the leftmost occurrence of the element in the tuple. You can observe this in the following example.
myTuple=(11,2,44,21,15,44,23,44,12)
print("The original tuple is:")
print(myTuple)
element=44
index=myTuple.index(element)
print("The index of element {} is {}".format(element, index))
Output:
The original tuple is:
(11, 2, 44, 21, 15, 44, 23, 44, 12)
The index of element 44 is 2
In this example, there are three instances of element 44 in the tuple at indices 2,5, and 7. However, the index()
method returns the value 2 as it considers only the leftmost index of an element.
If the value passed to the index()
method isn’t present in the tuple, the program runs into a ValueError exception with the message “ValueError: tuple.index(x): x not in tuple
”. You can observe this in the following example.
myTuple=(11,2,44,21,15,44,23,44,12)
print("The original tuple is:")
print(myTuple)
element=1111
index=myTuple.index(element)
print("The index of element {} is {}".format(element, index))
Output:
ValueError: tuple.index(x): x not in tuple
In this example, the program ran into the ValueError exception as the element 1117 isn’t present in the tuple.
Find All The Indices of A Given Element in a Tuple in Python
Instead of using the index()
method, we can also use for loop to find the index of an element in a tuple in Python. For this, we will use the following steps.
- First, we will calculate the length of the tuple using the
len()
function. Thelen()
function takes the tuple as its input argument and returns the length of the tuple. We will store the value in the variable “tupleLength
”. - Next, we will use a for loop and the
range()
function to iterate over the elements of the tuple. While iteration, we will first check if the current element is equal to the element we are searching for. If yes, we will print the current index.
After executing the for loop, we will get all the indices of the given element in the tuple as shown below.
myTuple=(11,2,44,21,15,44,23,44,12)
print("The original tuple is:")
print(myTuple)
element=44
tupleLength=len(myTuple)
for index in range(tupleLength):
current_value=myTuple[index]
if current_value==element:
print("The element {} is present at index {}.".format(element,index))
Output:
The original tuple is:
(11, 2, 44, 21, 15, 44, 23, 44, 12)
The element 44 is present at index 2.
The element 44 is present at index 5.
The element 44 is present at index 7.
Solved: Python Tuple Index Out of Range Error
We can access an element of a tuple in Python using the indexing operator as shown below.
myTuple=(11,2,44,21,15,44,23,44,12)
print("The original tuple is:")
print(myTuple)
index=3
element=myTuple[index]
print("The element at index {} is {}.".format(index,element))
Output:
The original tuple is:
(11, 2, 44, 21, 15, 44, 23, 44, 12)
The element at index 3 is 21.
In the above example, the index passed to the indexing operator should be less than the length of the tuple. If the value passed to the indexing operator is greater than or equal to the length of the tuple, the program will run into an IndexError exception with the message “IndexError: tuple index out of range
”. You can observe this in the following example.
myTuple=(11,2,44,21,15,44,23,44,12)
print("The original tuple is:")
print(myTuple)
index=23
element=myTuple[index]
print("The element at index {} is {}.".format(index,element))
Output:
IndexError: tuple index out of range
In this example, we have passed index 23 to the indexing operator. As 23 is greater than the length of the tuple, the program runs into the Python IndexError exception.
To solve this problem, you can first check if the value passed to the indexing operator is greater than or equal to the length of the tuple. If yes, you can inform the user that the index should be less than the length of the tuple as shown below.
myTuple=(11,2,44,21,15,44,23,44,12)
print("The original tuple is:")
print(myTuple)
tupleLength=len(myTuple)
index=23
if index<tupleLength:
element=myTuple[index]
print("The element at index {} is {}.".format(index,element))
else:
print("Index is greater than the tuple length.")
Output:
The original tuple is:
(11, 2, 44, 21, 15, 44, 23, 44, 12)
Index is greater than the tuple length.
In this example, we first check if the index value is greater than the length of the tuple. If yes, we print the message that index is greater than the length of the tuple. Otherwise, the program prints the value at the given index. Here, we are preempting the error.
Instead of the above approach, we can use the Python try except block to handle the IndexError exception once it is raised by the program as shown below.
myTuple=(11,2,44,21,15,44,23,44,12)
print("The original tuple is:")
print(myTuple)
tupleLength=len(myTuple)
index=23
try:
element=myTuple[index]
print("The element at index {} is {}.".format(index,element))
except IndexError:
print("Index is greater than the tuple length.")
Output:
The original tuple is:
(11, 2, 44, 21, 15, 44, 23, 44, 12)
Index is greater than the tuple length.
In this example, the IndexError exception is raised in the try block of the code. Then, the except block catches the exception and prints the message. Here, we are handling the error after it has already occurred.
Conclusion
In this article, we discussed how to find the index of an element in a tuple in Python. We also discussed how to solve the tuple index out-of-range error using the if-else statement and the try-except blocks. To learn more about Python programming, you can read this article on how to sort a tuple in Python. You might also like this article on the with open statement in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.