Open In App

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

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given 2 lists, get all the indices of all occurrence of each element in list2 from list1.

Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] 
Output : [[3], [1, 9], [0, 7]] 
Explanation : 5 is present at 1st and 9th index.

Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] 
Output : [[3], [1, 9], [4, 10]] 
Explanation : 8 is present at 4th and 10th index. 

Method #1 : Using loop + setdefault()

In this, we perform the task of getting all the elements list grouped with their indices, and in 2nd run, get only the elements that are present in the other list. 

Python3




# Python3 code to demonstrate working of
# Multiple Indices from list elements
# Using setdefault() + loop
 
# initializing list
test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing get_list
get_list = [7, 5, 3]
 
# getting all elements indices
ele_indices = dict() 
for idx, val in enumerate(test_list):
    ele_indices.setdefault(val, []).append(idx)
 
# filtering only required elements
res = [ele_indices.get(idx, [None]) for idx in get_list]  
 
# printing result
print("Filtered Indices of elements in list 1  : " + str(res))


Output

The original list is : [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
Filtered Indices of elements in list 1  : [[3], [1, 9], [2, 5, 8, 11]]

Method #2 : Using list comprehension + enumerate()

In this we use a nested loop, to get all the indices, and then filter in case of presence in another list.

Python3




# Python3 code to demonstrate working of
# Multiple Indices from list elements
# Using list comprehension + enumerate()
 
# initializing list
test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing get_list
get_list = [7, 5, 3]
 
# enumerate() used to get idx, val simultaneously
res = [([idx for idx, val in enumerate(test_list) if val == sub] if sub in test_list else [None])
      for sub in get_list]
 
# printing result
print("Indices of elements in list 1  : " + str(res))


Output

The original list is : [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
Indices of elements in list 1  : [[3], [1, 9], [2, 5, 8, 11]]

Time complexity: O(n*m), where n is the length of test_list and m is the length of get_list.
Auxiliary Space: O(k), where k is the length of res list.

Method #3: Using map() and filter()

Algorithm:

  1. Iterate over each element in get_list.
  2. For each element, use map() to apply a lambda function to the list of indices from 0 to len(test_list)-1.
  3. The lambda function uses filter() to filter out only the indices of elements in test_list that match the current element.
  4. If there are no matching elements, return [None].
  5. Otherwise, return the list of matching indices.
  6. Convert the map object to a list and assign to res.
  7. Return res.
     

Python3




# initializing list
test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing get_list
get_list = [7, 5, 3]
res = list(map(lambda sub: list(filter(lambda i: test_list[i] == sub, range(len(test_list))))
               or [None], get_list))
# printing result
 
print("Indices of elements in list : " + str(res))


Output

The original list is : [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
Indices of elements in list : [[3], [1, 9], [2, 5, 8, 11]]

Time complexity: O(n^2), where n is the length of test_list. This is because for each element in get_list, the lambda function needs to filter through all elements in test_list to find matches. Thus, the worst case time complexity is O(n) for each element in get_list, leading to O(n^2) overall.

Space complexity: O(n), where n is the length of test_list. This is because the lambda function creates a list of indices for each element in get_list, and the largest such list would be of length n.

Method #4:Using Numpy

Step by step approach:

  1. Convert the test_list to a numpy array using np.array() function.
  2. Create an empty list named ‘res’ to store the results.
  3. Iterate over each element in get_list, and for each element j, use np.where() function to get the indices of all occurrences of j in the test_array.
  4. Convert the array of indices to a list using list() function and append it to ‘res’.
  5. Print the final list of indices.

Python3




import numpy as np
 
test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
get_list = [7, 5, 3]
test_array = np.array(test_list)
res = [list(np.where(test_array == j)[0]) for j in get_list]
# printing result
print("Indices of elements in list 1  : " + str(res))
#This code is contributed by Vinay pinjala.


Output

The original list is : [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
Indices of elements in list 1  : [[3], [1, 9], [2, 5, 8, 11]]

Time Complexity: O(n), where n is the length of test_list. This is because we need to iterate over the list once to create the numpy array, and then we iterate over the get_list to find the indices of each element.

Auxiliary Space: O(n), where n is the length of test_list. This is because we create a numpy array of the same size as test_list, which requires additional space. Additionally, we create a list to store the indices of each element in get_list.

Method 5 : using a dictionary

  1. Define two lists: test_list and get_list, containing some integers.
  2. Initialize an empty dictionary indices_dict to store indices.
  3. Use a for loop and the enumerate() function to iterate over the elements of the test_list and their corresponding indices.
  4. For each element, check if it is already in the indices_dict. If it is, append the index to the existing list of indices for that element. Otherwise, create a new key-value pair with the element as the key and a list containing the index as the value.
  5. After the for loop completes, indices_dict will contain a list of indices for each element in test_list.
  6. Use a list comprehension to retrieve the list of indices for each element in get_list if it exists in indices_dict.
  7. Print the resulting list of index lists as the final output.

Python3




test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
get_list = [7, 5, 3]
 
# initialize an empty dictionary to store indices
indices_dict = {}
 
# iterate over the elements of the list and store their indices
for i, num in enumerate(test_list):
    if num in indices_dict:
        indices_dict[num].append(i)
    else:
        indices_dict[num] = [i]
 
# retrieve the indices for the elements in the given list
res = [indices_dict[num] for num in get_list if num in indices_dict]
 
# printing result
print("Indices of elements in list 1 : " + str(res))


Output

Indices of elements in list 1 : [[3], [1, 9], [2, 5, 8, 11]]

Time complexity: O(n), where n is the length of the input list. 

Auxiliary space: O(n), where n is the length of the input list. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads