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
test_list = [ 4 , 5 , 3 , 7 , 8 , 3 , 2 , 4 , 3 , 5 , 8 , 3 ]
print ( "The original list is : " + str (test_list))
get_list = [ 7 , 5 , 3 ]
ele_indices = dict ()
for idx, val in enumerate (test_list):
ele_indices.setdefault(val, []).append(idx)
res = [ele_indices.get(idx, [ None ]) for idx in get_list]
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
test_list = [ 4 , 5 , 3 , 7 , 8 , 3 , 2 , 4 , 3 , 5 , 8 , 3 ]
print ( "The original list is : " + str (test_list))
get_list = [ 7 , 5 , 3 ]
res = [([idx for idx, val in enumerate (test_list) if val = = sub] if sub in test_list else [ None ])
for sub in get_list]
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:
- Iterate over each element in get_list.
- For each element, use map() to apply a lambda function to the list of indices from 0 to len(test_list)-1.
- The lambda function uses filter() to filter out only the indices of elements in test_list that match the current element.
- If there are no matching elements, return [None].
- Otherwise, return the list of matching indices.
- Convert the map object to a list and assign to res.
- Return res.
Python3
test_list = [ 4 , 5 , 3 , 7 , 8 , 3 , 2 , 4 , 3 , 5 , 8 , 3 ]
print ( "The original list is : " + str (test_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))
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:
- Convert the test_list to a numpy array using np.array() function.
- Create an empty list named ‘res’ to store the results.
- 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.
- Convert the array of indices to a list using list() function and append it to ‘res’.
- 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 ]
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]
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), 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
- Define two lists: test_list and get_list, containing some integers.
- Initialize an empty dictionary indices_dict to store indices.
- Use a for loop and the enumerate() function to iterate over the elements of the test_list and their corresponding indices.
- 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.
- After the for loop completes, indices_dict will contain a list of indices for each element in test_list.
- Use a list comprehension to retrieve the list of indices for each element in get_list if it exists in indices_dict.
- 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 ]
indices_dict = {}
for i, num in enumerate (test_list):
if num in indices_dict:
indices_dict[num].append(i)
else :
indices_dict[num] = [i]
res = [indices_dict[num] for num in get_list if num in indices_dict]
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!