Python List index() Method
Now, we are going to learn about the index method. Using the index method, we get the first occurrence index of some element in the list. Simply speaking, we would give some element to the index method as an argument, and it is returning the first occurrence index of that element in the list, which means at what position the element has first occurred in the list. Let’s have a look at a simple program, which demonstrates the index method
Python List index() Method
As you can see in the above program, we have a simple list, and then we are trying to use the index method. We are trying to get the first occurrence of 12 in the list, and the output, as we can guess, comes out to be 0. You can try executing the program and observing the output of the program yourselves.
Now, Let’s say that we provide some element to the index method, which is not there in the list, in such a situation, we get an error, saying that the element is not in the list. Let’s have a look at another program, which demonstrates the same thing.
As you can see in the above program, we have provided an element to the index method as an argument, which is not there in the list, so in such a case, we get an error. You can also execute the above program and observe the output. We can use the index method in our program, as and when required.