Python Tuple index
Now, we are going to learn about the index method, which, as the name suggests, is going to give the index of the specified element in the tuple. This is like we are going to provide some element to the index method, and it is going to return the index of that element in the tuple. Note that the index method returns only the first occurrence index of some element.
Let’s have a look at a program, which tries to demonstrate the same thing.
Python Tuple index() method
As you can see in the above program, we have a simple tuple, which contains some elements, and then we are trying to get the index of 31 from our myTuple. One can simply guess the output of the above program. If you try to execute the above program, the output comes out to be 3, since the index of element 31 is 3. You can try some other values as well.
Also, the thing is that if you provide some element, which is present more than one time in the tuple, then we are going to get the first occurrence index of that specified element. For example, in the above example, the tuple has an element, which is 12, and it is present three times. So, if we try to get the index of 12 using the index method, it is going to give us the first occurrence index of that element. Let’s have a look at the program as well.
As you can see in the above program, we have the same tuple, and we are trying to have the index of element 12, which occurs multiple times in the tuple. So, we get the first occurrence index of that element, which is simply 0 in this case.
Also, if the value that we have provided to the index method, is not at all present in the tuple, in that case, we are going to get into an error. So, as and when required, we can make use of the index method on the tuple, in our programs.