Find the index of an item in a list in Python
In this article we will learn how to find the index of an item in a list in Python and in a very simple way, and you will be surprised!
Hey you programmer, how are you? Let’s learn more about Python and its lists!
To find an index in a list in Python is very easy, we obviously need to have a list and use the index method
In this method we will pass as a parameter the element to be found, whether in any data type, such as: text (string) or an integer
Here’s a practical example of how to find the index:
myList = ['banana', 'maçã', 'mamão'] print(myList.index('maçã')) myListB = [5,22,13,1,55,1024] print(myListB.index(1))
Here we have two lists with different data types, and checks were made on both using the index method
As said before, we just pass the parameter equal to the item we want to identify the index
So the output of this example will be:
That’s because all lists start at index 0, so the second element will be index 1
When you pass an element that is not in the list as an argument to index, Python will return an error
So you should handle this and use it carefully, so as not to make your program stop working.
Traceback (most recent call last): File "main.py", line 9, in <module> print(listaB.index('test')) ValueError: 'test' is not in list
Or you can also handle this situation with a try statement, check it out:
try: print(listaB.index('test')) except: print("Not found!")
In this article we learned how to find an index of an item in a list in Python
For this we use the index method in a list, and pass it an argument that is the element we want to know the index
Want to learn more about Python? Click here!