Find index of first occurrence in a list python

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

ParametersExplanation
element This represents the element that’s the index we want to find in the list.
startThis is an optional parameter, has a default value of 0. It represents the start index to find the element.
endan optional parameter, it represents the stop index to find the element, if not specify the end index it considers till the end of the list.

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 slicing

Here 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)

Output

last index indexes of item "cat" = 6

3. Get indexes of all occurrence of an item in List using list comprehension

The 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() function

The 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.

Syntax

enumerate(iterable_object,start)

Parameters

NameExplanation
iterable_objectIt represents the iterable object [list, tuple, string, dictionary], or object that support iteration
startIt represents the counter number from which enumerate() counter start, default it starts at 0.

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)

Output

all indexes of item "cat" in list = [1, 3, 5, 6]

6. Get indexes of all occurrence of an item in the list Using NumPy

Here 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)

Output

all 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)

Output

all 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)

Output

all indexes of item "cat" in list = [1, 3, 5, 6]

Conclusion

We 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 1

To 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 6

This 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:

  • How the index() method works.
  • How to get multiple indexes of all similar elements.
  • How to find the index of a list element.
  • How to find the index of a character in a string.

The index() Method in Python

In 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:

  • list is the list we are searching for.
  • obj is the object we are matching with.

Let’s see some examples of using the index() method in Python.

How to Find the Index of a List Element in Python

You 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 1

The 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 list

You 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 Python

To find an index of a character in a string, follow the same procedure as finding an index in a list.

  • Check if the character is in the string using the in statement.
  • Find the index of the character using the index() method of a string.

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:

6

This 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 Python

In 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:

  1. Couple the elements of a list with an index using the enumerate() function.
  2. Loop over the enumerated elements.
  3. Check if the index, item pair’s item matches with the object you are searching for.
  4. Add the index into a result list.

Here is a generator function that does exactly that:

def indexes(iterable, obj): result = [] for index, elem in enumerate(iterable): if elem == obj: yield index

Or 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]

Conclusion

Today 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:

  • Implement a function that couples each element with an index.
  • Loop through the coupled elements.
  • Pick the indexes of the elements that match with the search object.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

50 Python Interview Questions and Answers

50+ Buzzwords of Web Development