In Python, tuples are an ordered and immutable collection of elements. They are often used to store related pieces of information together, such as the x and y coordinates of a point or the name and age of a person. Sometimes, we may need to find the position of a particular element within a tuple. Python provides a built-in method called index()
that makes it easy to accomplish this task. In this article, we will explore how to use the index()
method to get the index of an element in a tuple.
The index()
method is a built-in method in Python that returns the index of the first occurrence of a specified element in a tuple. The method takes a single argument, which is the element to search for. Here’s an example:
my_tuple = ('a', 1, 'f', 'a', 5, 'a')
print(my_tuple.index('f')) # 2
In this example, we created a tuple called my_tuple
that contains six elements. We then called the index()
method on the tuple, passing in the string 'f'
as the argument. The method returns the index of the first occurrence of 'f'
in the tuple, which is 2. We printed the result to the console using the print()
function.
If the specified element is not present in the tuple, the index()
method raises a ValueError
exception. For example:
my_tuple = ('a', 1, 'f', 'a', 5, 'a')
print(my_tuple.index('z')) # ValueError: tuple.index(x): x not in tuple
In this example, we called the index()
method on the my_tuple
tuple, passing in the string 'z'
as the argument. Since 'z'
is not present in the tuple, the method raises a ValueError
exception.
That’s basically it.
I hope you find this useful.