Searching for all the occurrences of an element in a list can be a tedious task. In this article, we will try to find the index of an element in a list. We will look at different ways to find the first, last, and other occurrences of the element in the list.
Find the index of an element in a list using the index() method
We can use the index() method to find the first occurrence of an element in a list. The index() method takes the element as the first input argument which is compulsory. It takes two optional arguments which are indices at which search has to start and stop in the list. If the input element exists in the list between the specified indices, the index() method returns the index of the element where it occurs first. We can observe this in the following example.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 2
print("List is:", myList)
print("Number is:", myNum)
index = myList.index(myNum)
print("Index of {} is {}".format(myNum, index))
Output:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 2
Index of 2 is 1
If the element is not present between the specified indices in the list, the index() method raises ValueError.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 100
print("List is:", myList)
print("Number is:", myNum)
index = myList.index(myNum)
print("Index of {} is {}".format(myNum, index))
Output:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 100
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 5, in <module>
index = myList.index(myNum)
ValueError: 100 is not in list
We can handle the ValueError
by exception handling using python try except blocks as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 100
print("List is:", myList)
print("Number is:", myNum)
try:
index = myList.index(myNum)
print("Index of {} is {}".format(myNum, index))
except ValueError:
print("{} is not in the list.".format(myNum))
Output:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 100
100 is not in the list.
We can find the first index of an element in a list using the index() method but we cannot use it to find all the occurrences of any element in the list. We will use for loop to iterate the list to find all the occurrences of any element in the list.
Find the index of an element in a list using for loop
To find the index of an element in a list using for loop, we will simply iterate through the list and check for each element. During iteration, if we find the element for which we have to find the index, we will simply print the index as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 3
print("List is:", myList)
print("Number is:", myNum)
index = -1 # some invalid value
listLen = len(myList)
for i in range(listLen):
if myList[i] == myNum:
index = i
break
if index == -1:
print("{} not found in the list".format(myNum))
else:
print("Index of {} is {}".format(myNum, index))
Output:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 3
Index of 3 is 2
Get the last occurrence of an element in a list
To find the index from the end at which an element exists, we can simply iterate through the loop and maintain the result index at which the element was found last. Whenever the element is found, we will update the result index. In this way, after a full iteration of the list, we will have the last index of the element in our result index. This can be done as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 3
print("List is:", myList)
print("Number is:", myNum)
index = -1 # some invalid value
listLen = len(myList)
for i in range(listLen):
if myList[i] == myNum:
index = i
if index == -1:
print("{} not found in the list".format(myNum))
else:
print("Last index of {} is {}".format(myNum, index))
Output:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 3
Last index of 3 is 9
The above method requires us to iterate the whole list each time we have to find the last index at which an element is present in the list. To avoid this, we can iterate the list backward starting from the end. Here we will use indexing and after finding the element, we will get the positive index of the element by adding the negative index to the length of the list as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 3
print("List is:", myList)
print("Number is:", myNum)
index = -1 # some invalid value
listLen = len(myList)
for i in range(-1, -listLen, -1):
if myList[i] == myNum:
index = listLen+i
break
if index == -1:
print("{} not found in the list".format(myNum))
else:
print("Last index of {} is {}".format(myNum, index))
Output:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 3
Last index of 3 is 9
Get all occurrences of an element in a list
To find all occurrences of an element in a list, We can iterate through the list using a for loop and print the indices where the element is present in the list as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 3
print("List is:", myList)
print("Number is:", myNum)
indices = []
listLen = len(myList)
for i in range(listLen):
if myList[i] == myNum:
indices.append(i)
if indices is None:
print("{} not found in the list".format(myNum))
else:
print("Indices of {} are {}".format(myNum, indices))
Output:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 3
Indices of 3 are [2, 9]
Instead of using a for loop, we can use list comprehension to find all the indices at which an element is present as follows.
myList = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
myNum = 2
print("List is:", myList)
print("Number is:", myNum)
listLen = len(myList)
indices = [i for i in range(listLen) if myList[i] == myNum]
if indices is None:
print("{} not found in the list".format(myNum))
else:
print("Indices of {} are {}".format(myNum, indices))
Output:
List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23]
Number is: 2
Indices of 2 are [1, 8]
Conclusion
In this article, we have used different ways to find the indices of an element in a list. We also looked at ways to find all occurrences of an element in a list. Stay tuned for more informative articles.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.