How do I get the index of an element in a list
use index()
to find the index in your list
Context
The index()
method returns the index of the searched element in your list.
# Find the index of the value 4 in my_list >>> my_list = [1,2,3,4] >>> print(my_list.index(4)) 3
index()
is of linear time complexity which means that it needs to iterate over all list items until a match is found. In the worst case scenario, it needs to go through all the items before finding a match. This might appear insignificant for our example but adding one more for-loop can easily change your code to exponential time complexity.
The linear time complexity nature also means that you achieve the same outcome by looping through the list yourself
def search_index(values_list: List[int], searched_value: int) -> int: for index, value in enumerate(my_list): if value == search_value: return index raise ValueError("Searched value was not in the list") >>> my_list = [1,2,3,4] >>> print(search_index(my_list, 4)) 3
index()
raises a ValueError exception if the searched item is not inside your list. In addition, it also needs to still check all items before arriving to this conclusion
>>> my_list = [1,2,3,4] >>> searched_value = 5 >>> print(my_list.index(5)) ValueError
index()
is restricted to only return the first match. This means that it will simply ignore indices of other potential items. If you want to find all indices then you could implement something as follows
def search_indices(values_list: List[int], searched_value: int) -> None: for index, value in enumerate(my_list): if value == search_value: print(index) raise ValueError("Searched value was not in the list") >>> my_list = [1,2,3,4,4] >>> search_indices(my_list, 4) 3 4