Python program to get the indices of each element of one list in another list


When it is required to get the indices of each element of one list in another list, a simple iteration and the enumerate attribute along with the ‘setdefault’ method is used.

It also uses list comprehension and the ‘get’ method is used.

Example

Below is a demonstration of the same −

my_list = [14, 52, 23, 47, 18, 23, 12, 54, 43, 22, 28, 13]

print("The list is :")
print(my_list)

my_list_2 = [17, 52, 13]
print("The second list is :")
print(my_list_2)

element_indices = dict()
for index, value in enumerate(my_list):
   element_indices.setdefault(value, []).append(index)

my_result = [element_indices.get(index, [None]) for index in my_list_2]

print("The result is :")
print(my_result)

Output

The list is :
[14, 52, 23, 47, 18, 23, 12, 54, 43, 22, 28, 13]
The second list is :
[17, 52, 13]
The result is :
[[None], [1], [11]]

Explanation

  • A list of integers is defined and is displayed on the console.

  • Another list of integers is defined and displayed on the console.

  • An empty dictionary is created.

  • The first list is iterated over using ‘enumerate’.

  • The ‘setdefault’ method is used to give a value to the element.

  • This is appended to the empty dictionary.

  • A list comprehension is used to iterate over the elements and the ‘get’ method is used to get the index values for elements in the second index.

  • This is stored in a list and is assigned to a variable.

  • This list is displayed as the output on the console.

Updated on: 08-Sep-2021

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements