How to find the index of an item in a list in Python?
|To perform certain index-based operations while programming we need to access the index of an element in the list. In this Python example we will discuss some o the ways to find the index of an item in a list in Python.
Some of the topics which will be helpful for understanding the program implementation better are:
1. Using the index()
method
The index()
method returns the index of the first occurrence of an item in a list and a ValueError is raised if the element is not found.
Now let’s implement a program to find the index of an item in a list in Python.
my_list = [1, 2, 3, 4, 5] item = 3 index = my_list.index(item) print(index)
Output 2
2. Using enumerate() function
The enumerate()
function in Python takes an iterable as an argument and returns a tuple containing the index and the item at that index.
Here is an example.
my_list = [1, 2, 3, 4, 5] item = 3 for i, val in enumerate(my_list): if val == item: index = i break print(index)
Output 2
3. Using the bisect module
The bisect
module in Python has bisect_left()
function that can be used to find the index of an item in a sorted list.
Here is an example.
import bisect my_list = [1, 2, 3, 4, 5] item = 3 index = bisect.bisect_left(my_list, item) print(index)
Output 2
4. Using for
loop and range()
function
You can create a range of indices that matches the length of the list and iterate over them. Then, you can use the current index to access the corresponding item in the list.
Here is an example.
countries = ['USA', 'Canada', 'UK', 'Germany', 'Japan'] for i in range(len(countries)): print(i, countries[i])
Output 0 USA 1 Canada 2 UK 3 Germany 4 Japan
4. Conclusion
In this Python example, we discussed the index()
method, for loop, the enumerate()
function, or the bisect
module. to find the index of an item in a list in Python.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?