How to find the index of one or multiple element occurrences in a Python list?

Get index of element occurrences in a list

You can use a Python list comprehension to build a new list containing the indices of all occurrences of a specific string in another list. Here’s a code sample: idx_lst = [ i for i, e in enumerate(my_lst) if (e == my_str) ].

#1 : Find index of an item in a list

Here’s a simple example of finding the index of a specific value in another Python list. Let’s start by defining a couple of simple lists we will use in this example:

prog_lang_lst = ['Java', 'Go', 'Python', 'C-sharp', 'R', 'JavaScript']
data_lang_lst = [ 'Python', 'R']
my_value = 'Python'

Now we’ll use a list comprehension in order to build a new list containing the indices:

pos_idx_lst = [ i for i, e in enumerate(prog_lang_lst) if (my_elmnt == e)]
print(pos_idx_lst)

#this returns: [2]

#2: Get the indices of multiple list elements with Python

We can use the same technique in order to print the indices of occurrences of multiple values in a list. Here are two simple ways to do this:

Option 1 – list comprehension:

pos_lst = [ i for i, e in enumerate(prog_lang_lst) if e in data_lang_lst]

Option 2:

pos_lst = []
for i, e in enumerate (prog_lang_lst):
    if e in data_lang_lst:
        pos_lst.append (i)

Both will return the following list:

[2, 4]

#3 : Count all occurrences of a value in a list?

What if we would like to count the number of occurrences of a specific string in a list? Here’s another simple snippet that delivers that.

prog_lang_lst = ['Python', 'Go', 'Python', 'C-sharp', 'R', 'JavaScript']

my_elmnt = 'Python'

print('The value {} appears {} times in the list.'.format(my_elmnt,prog_lang_lst.count(my_elmnt)))

This will return:

The value Python appears 2 times in the list.

#4 : Select a specific list element by index

To choose a list value by its index – in this case the second element of our prog_lang_lst list, you use this simple syntax:

my_elmnt =prog_lang_lst[1]

print(my_elmnt)

This will return: Go

Suggested follow up learning

How to divide a list of strings according to a specific condition?