Find index of first occurrence in a list python
Show
In this article, Get index of all occurrences of list items in Python. Indexing is the most powerful feature of an array, list, or continuous data structure and we will learn about Python list indexing in detail. Approach to get index or position of an item 1. Get index of first occurrence of an item in list using list.index()The list index() is an in-built method of list class. It is mainly used to find the index of a given element, by searching the whole list and return position/Index the first occurrence of a given element, if the list contains the duplicate element then it returns only the first occurrence(index/position). Syntax#list index method syntax list.index(element,start,end) Parameters
Error: If the index of the element is not found in the list then it raises a ValueError: let us understand with code example
animal_list = ['dog','cat','mouse','ant','bee','fly','spider','rat'] #item index to find item_to_find = 'bee' index = animal_list.index(item_to_find) print('the index of element is =',index) the index of element is = 4 2.Get last index of an item in list Using list slicingHere in this code snippet, we are using list slicing to get the last occurrence of the element. animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat'] item_to_find = 'cat' last_index = len(animal_list) - 1 - animal_list[::-1].index(item_to_find) print('last index indexes of item "cat" =',last_index) Outputlast index indexes of item "cat" = 6 3. Get indexes of all occurrence of an item in List using list comprehensionThe list index() method is used to find the first occurrence of element,but it is not enough to fulfill our requirements while doing data manipulation.Sometime We have to find index/position of all occurrence of an item in list item. By using List comprehension we can achieve this. let us dive into code example #program to find index of item in list animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat'] item_to_find = 'cat' list_all_indexes = [item for item in range(len(animal_list)) if animal_list[item] == item_to_find] print('all indexes of item "cat" in list =',list_all_indexes) Output all indexes of item "cat" in list = [1, 3, 5, 6] 4. Get indexes of all occurrence of an item in a list Using more_itertools.locate()The more_itertools.locate() module can be used to find the indexes of all occurrences of an item. To use this module first we have to install it, otherwise, we will get the ModuleNotFoundError: No module named ‘more_itertools’. We pass the lambda function to locate() method, this lambda function contains the logic to match our search criteria. We pass the full list and the lambda function to locate function then locate function returns the index numbers for which our lambda functions held true. This is how we get the multiple indexes if the element is found at multiple indexes. Now let us see this in practice with our example. from more_itertools import locate animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat'] item_to_find = 'cat' list_of_all_indexes = list(locate(animal_list, lambda item: item == item_to_find)) print('all indexes of item "cat" in list =',list_of_all_indexes) Output all indexes of item "cat" in list = [1, 3, 5, 6] 5. Get indexes of all occurrence of an item in the list Using enumerate() functionThe enumerate() function can be used to get indexes of all occurrences of an item. The enumerate() function adds a counter to an iterable object and returns it. Syntaxenumerate(iterable_object,start) Parameters
animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat'] list_of_indexes = [] item_to_find = 'cat' for (index, item) in enumerate(animal_list): if item == item_to_find: list_of_indexes.append(index) print('all indexes of item "cat" in list =',list_of_indexes) Outputall indexes of item "cat" in list = [1, 3, 5, 6] 6. Get indexes of all occurrence of an item in the list Using NumPyHere in this code example, we are using the NumPy module to find indexes of all occurrence of an item in list.We are using Numpy provided where() function that return the item which fulfill the given conditions. Let is understand with example. import numpy as np animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat'] item_to_find = 'cat' np_array = np.array(animal_list) list_of_indexes = np.where(np_array == item_to_find)[0] print('all indexes of item "cat" in list =',list_of_indexes) Outputall indexes of item "cat" in list = [1 3 5 6] 7. Get indexes of all occurrence of an item in the list Using filter()Python filter() method run as a function on all elements of an iterable object to filter the object and returns those elements as iterator which fulfill the condition in function. We can better understand with below code snippet. animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat'] item_to_find = 'cat' list_of_indexes = list(filter(lambda item: animal_list[item] == item_to_find, range(len(animal_list)))) print('all indexes of item "cat" in list =',list_of_indexes) Outputall indexes of item "cat" in list = [1, 3, 5, 6] 8. Get indexes of all occurrences of an item in the list Using while loop and list.index()As we have already seen the list.index() find the index of the first occurrence of an item. But by using the loop we can find all the occurrence of element and append in the result list. We are looping from the first element to the end of the list. animal_list = ['dog','cat','mouse','cat','bee','cat','cat','rat'] item_to_find = 'cat' list_of_indexes = [] item_index = 0 while True: try: item_index = animal_list.index(item_to_find,item_index+1) list_of_indexes.append(item_index) except ValueError: break print('all indexes of item "cat" in list =',list_of_indexes) Outputall indexes of item "cat" in list = [1, 3, 5, 6] ConclusionWe hope we will use these ways to get the index or position of an element in Python list.
To find the index of a list element in Python, use the built-in index() method. For example, let’s find the first string that equals “Bob” in a list of strings: names = ["Alice", "Bob", "Charlie"] names.index("Bob") # Returns 1To find the index of a character in a string, use the index() method on the string. For example, let’s find the first occurrence of the letter w in a string: "Hello world".index("w") # returns 6This is the quick answer. In this guide, we are going to take a deeper dive into finding the index of an element in Python. You are going to learn:
The index() Method in PythonIn Python, a list has a built-in index() method. This method returns the index of the first element that matches with the parameter. The syntax for the index() function is as follows: list.index(obj)Where:
Let’s see some examples of using the index() method in Python. How to Find the Index of a List Element in PythonYou can use the index() method to find the index of the first element that matches with a given search object. For instance, let’s find the index of “Bob” in a list of names: names = ["Alice", "Bob", "Charlie"] names.index("Bob") # Returns 1The index() method returns the first occurrence of an element in the list. In the above example, it returns 1, as the first occurrence of “Bob” is at index 1. But this method has a little problem you need to understand. If the element you are searching for does not exist, this method throws an error that crashes the program if not handled correctly. For example, let’s search for “David” in the list of names: names = ["Alice", "Bob", "Charlie"] idx = names.index("David")Output: ValueError: 'David' is not in listYou certainly don’t want your program to crash when searching for a non-existent value. To fix this issue, you should check that the element is in the sequence, to begin with. To do this, use the in statement with a simple if-else statement. For example: names = ["Alice", "Bob", "Charlie"] if "David" in names: idx = names.index("David") else: print("Not found.")Output: Not found.Now the above code no longer throws an error. The index search does not even start if the item is not there. Now you know how to use the index() method to find an index of an object in a list. Next, let’s take a look at how you can use a similar approach to finding the index of a character in a string. How to Find the Index of a String Character in PythonTo find an index of a character in a string, follow the same procedure as finding an index in a list.
For example: sentence = "Hello world" if "x" in sentence: idx = sentence.index("x") else: print("Not found.")Output: Not found.With strings, you can also search for longer substrings or words. For example, let’s find the index of a substring “wor” in “Hello world”: sentence = "Hello world" substr = "wor" if substr in sentence: idx = sentence.index(substr) print(idx) else: print("Not found.")Output: 6This returns the starting position of the substring “wor”. Now you understand how to use the index() method in Python. However, this method only returns the first index. Let’s take a look at how you can get all the indexes instead. How to Get All Indexes of a List in PythonIn the previous examples, you have seen how to get the first index of an element that is equal to the object we are searching for. However, sometimes you might want to find the indexes of all the elements that equal something. To get all the indexes:
Here is a generator function that does exactly that: def indexes(iterable, obj): result = [] for index, elem in enumerate(iterable): if elem == obj: yield indexOr if you want to use a shorthand, you can also use a generator comprehension: def indexes(iterable, obj): return (index for index, elem in enumerate(iterable) if elem == obj)Anyway, let’s use this function: names = ["Alice", "Alice", "Bob", "Alice", "Charlie", "Alice"] idxs = indexes(names, "Alice") print(list(idxs))Output: [0, 1, 3, 5]As you can see, now this function finds all the indexes of “Alice” in the list. You can also call it for other iterables, such as a string: sentence = "Hello world" idxs = indexes(sentence, "l") print(list(idxs))Output: [2, 3, 9]ConclusionToday you learned how to get the index of an element in a list in Python. You also saw how to get all the indexes that match with an object. To recap, use the index() method to find the index of an element in Python. You can use it the same way for lists and strings. It finds the first occurrence of a specified element in the sequence. To get all the indexes:
Thanks for reading. I hope you find it useful. Happy coding! Further Reading50 Python Interview Questions and Answers 50+ Buzzwords of Web Development |