Find index of element in List – Python

In this article we will discuss different ways to get index of element in list in python.

We will see how to find first index of item in list, then how to find last index of item in list, or then how to get indices of all occurrences of an item in the list. Apart from this, we will also discuss a way to find indexes of items in list that satisfy a certain condition.

Python: Get index of item in List

To find index of element in list in python, we are going to use a method list.index().

Python List index()

Python’s list data type provides this method to find the first index of a given element in list or a sub list i.e.

list.index(x[, start[, end]])

Arguments :

  • x : Item to be searched in the list
  • start : If provided, search will start from this index. Default is 0.
  • end : If provided, search will end at this index. Default is the end of list.

Returns: A zero based index of first occurrence of given element in the list or range. If there is no such element then it raises a ValueError.

Important Point : list.index() returns the index in a 0 based manner i.e. first element in the list has index 0 and second element in index is 1.

Let’s use this function to find the indexes of a given item in the list,

Suppose we have a list of strings,

# List of strings
list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

Now let’s find the index of the first occurrence of item ‘Ok‘ in the list,

elem = 'Ok'

# Find index position of first occurrence of 'Ok' in the list
index_pos = list_of_elems.index(elem)

print(f'First Index of element "{elem}" in the list : ', index_pos)

Output

First Index of element "Ok" in the list :  1

As in the list.index() we did not provided start & end arguments, so it searched for the ‘Ok‘ in the complete list. But returned the index position as soon as it encountered the first occurrence of ‘Ok‘ in the list.

But if searched item doesn’t exists in the list, then index() will raise ValueError. Therefore we need to be ready for this kind of scenario. For example,

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

elem = 'Why'

try:
    index_pos = list_of_elems.index(elem)
    print(f'First Index of element "{elem}" in the list : ', index_pos)
except ValueError as e:
    print(f'Element "{elem}" not found in the list: ', e)

Output

Element "Why" not found in the list:  'Why' is not in list

As ‘Why‘ was not present in the list, so list.index() raised ValueError.

Find index of an item in list using for loop in Python

Instead of using list.index() function, we can iterate over the list elements by index positions, to find the index of element in list i.e.

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

elem = 'is'

pos = -1
# Iterate over list items by index pos
for i in range(len(list_of_elems)):
    # Check if items matches the given element
    if list_of_elems[i] == elem:
        pos = i
        break

if pos > -1:
    print(f'Index of element "{elem}" in the list is: ', pos)
else:
    print(f'Element "{elem}" does not exist in the list: ', pos)

Output:

Index of element "is" in the list is:  2

Get last index of item in Python List from end

To get the last index of an item in list, we can just reverse the contents of list and then use index() function, to get the index position. But that will give the index of element from last. Where we want index of last occurrence of element from start. Let’s see how to that,

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']

elem = 'Ok'

try:
    # Get last index of item in list
    index_pos = len(list_of_elems) - list_of_elems[::-1].index(elem) - 1
    print(f'Last Index of element "{elem}" in the list : ', index_pos)
except ValueError as e:
    print(f'Element "{elem}" not found in the list: ', e)

Output:

Last Index of element "Ok" in the list :  3

It gives the index of last occurrence of string ‘Ok’ in the list.

Till now we have seen, how to find index of first occurrence of an item in the list. But what if there are multiple occurrences of an item in the list and we want to know their indexes ? Let’s see how to do that,

Find indexes of all occurrences of an item in Python List

Suppose we have a list of strings i.e.

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

Now we want to find indexes of all occurrences of ‘Ok’ in the list, like this,

[1, 3, 9]

They are differences ways to do that, let’s see them one by one.

Find all indices of an item in List using list.index()

As list.index() returns the index of first occurrence of an item in list. So, to find other occurrences of item in list, we will call list.index() repeatedly with range arguments. We have created a function that uses list.index() and returns a list of indexes of all occurrences of an item in given list i.e.

def get_index_positions(list_of_elems, element):
    ''' Returns the indexes of all occurrences of give element in
    the list- listOfElements '''
    index_pos_list = []
    index_pos = 0
    while True:
        try:
            # Search for item in list from indexPos to the end of list
            index_pos = list_of_elems.index(element, index_pos)
            # Add the index position in list
            index_pos_list.append(index_pos)
            index_pos += 1
        except ValueError as e:
            break

    return index_pos_list

This function calls the list.index() in a loop. Initially it looks for item from 0th index in list. But when it encounters the item, then from next iteration it looks from that location onward till the end of list is reached. It keeps the indexes of matched elements in a separate list and returns that in the end.

Now let’s use above function to find all indexes of ‘Ok’ in the list,

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

# Get indexes of all occurrences of 'Ok' in the list
index_pos_list = get_index_positions(list_of_elems, 'Ok')

print('Indexes of all occurrences of "Ok" in the list are : ', index_pos_list)

Output

Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

Find all indexes of an item in Python List directly while iterating

Instead of using list.index() function, we can directly iterate over the list elements by indexes using range() function. Then for each element it checks, if it matches with our item or not. If yes then keep its index in list i.e.

def get_index_positions_2(list_of_elems, element):
    ''' Returns the indexes of all occurrences of give element in
    the list- listOfElements '''
    index_pos_list = []
    for i in range(len(list_of_elems)):
        if list_of_elems[i] == element:
            index_pos_list.append(i)
    return index_pos_list


list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

# Get indexes of all occurrences of 'Ok' in the list
index_pos_list = get_index_positions_2(list_of_elems, 'Ok')

print('Indexes of all occurrences of a "Ok" in the list are : ', index_pos_list)

Output

Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

Simple solution. But let’s look into some single line alternatives,

Use List Comprehension to find all indexes of an item in Python List

Concept is similar but instead of using for loop for iteration we can achieve same using list comprehension i.e.

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

# Use List Comprehension Get indexes of all occurrences of 'Ok' in the list
index_pos_list = [ i for i in range(len(list_of_elems)) if list_of_elems[i] == 'Ok' ]

print('Indexes of all occurrences of a "Ok" in the list are : ', index_pos_list)

Output

Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

Use more_itertools.locate() to find all indexes of an item in Python List

more_itertools.locate(iterable, pred=bool, window_size=None)

locate() yields the index of each item in list for which given callback returns True.

To find all the occurrences of item ‘Ok‘ in the list we will pass a lambda function to locate(), that will check if item is ‘Ok‘ or not i.e.

from more_itertools import locate

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

# Use more_itertools.locate() to find all indexes of an item 'Ok' in list
index_pos_list = list(locate(list_of_elems, lambda a: a == 'Ok'))

print('Indexes of all occurrences of a "Ok" in the list are : ', index_pos_list)

Output

Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

locate() yields the indexes of elements in the list for which given predicate is True. So, in our case it yields the indexes of ‘Ok’ in the list. We collected those indexes in a list.

Find indexes of items in Python List that satisfy certain Conditions

Suppose we want to find indexes of items in a list that satisfy certain condition like indexes of items in a list of strings whose length is less than 3. To do that we have created a generic function i.e.

def get_index_positions_by_condition(list_of_elems, condition):
    ''' Returns the indexes of items in the list that returns True when passed
    to condition() '''
    index_pos_list = []
    for i in range(len(list_of_elems)):
        if condition(list_of_elems[i]) == True:
            index_pos_list.append(i)
    return index_pos_list

This function accepts a list of elements and a callback function as arguments. For each element it calls the callback function and if callback() function returns True then it keeps the index of that element in a new list. In the end it returns the indexes of items in the list for which callback() returned True.

Let’s call this function to find indexes of items in list of strings whose length are less than 3 i.e.

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

# get index position of string elements in list whose length are greater than 3
index_pos_list = get_index_positions_by_condition(list_of_elems, lambda x : len(x) < 3)

print('Index positions of the string elements in list with length less than 3 : ', index_pos_list)

Output

Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

Summary

We learned about several ways to get the index of items in a Python List.

1 thought on “Find index of element in List – Python”

  1. Does this only work when ‘Ok’ is the only thing in the string or would it find the index of something like ‘Ok this is the list’ and return the index of that when searching for the element ‘Ok’

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top