Sometimes you want to access the information or index for a particular element. In this example, you will learn how to find the index of an element in a list in python in different ways.
Sample List Creation
Let’s first create a sample list for implementing the methods.
sample_list = ["India","America","Australia","Russia","South Africa","UK"]
The output of the list is the name of some countries.
['India', 'America', 'Australia', 'Russia', 'South Africa', 'UK']
Methods to index the element in list python
Method 1: Using the simple index() method.
Python language provides the list.index() method that returns the index of the element you want to search. For example, if you want to find the index of the country named Russia then you will execute the following lines of code.
sample_list = ["India","America","Australia","Russia","South Africa","UK"]
# method 1
print(sample_list.index("Russia"))
Output
3
Method 2: Find the index of the element in the range.
The function list.index() also accepts the start and end argument. It tells the python interpreter to find the index of the element in a range. For example, I want to find the country America. You can see in the sample list America is located at the index 1 which is between 0 and 2 ( India and Australia). So I will pass the start as 0 and end as 2 as an argument to the list.index () method.
Execute the below lines of code to find the index of the element for the country America.
sample_list = ["India","America","Australia","Russia","South Africa","UK"]
# method 2
print(sample_list.index("America",0,2))
Output
1
Conclusion
If you are searching for specific elements in the python list then you have to use the list.index() method. The start and stop arguments will make searching quicker if you already have some idea where the elements might be found.
These are methods to find the index of an element in a list in python. I hope you have liked this tutorial. If you have any doubt then you can contact us for more help.
Leave a Reply