Open In App

Python | Find elements of a list by indices

Last Updated : 18 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two lists with elements and indices, write a Python program to find elements of list 1 at indices present in list 2

Examples:

Input : lst1 = [10, 20, 30, 40, 50]
        lst2 = [0, 2, 4]
Output : [10, 30, 50]
Explanation: 
Output elements at indices 0, 2 and 4 i.e 10, 30 and 50 respectively. 

Input : lst1 = ['Hello', 'geeks', 'for', 'geeks']
        lst2 = [1, 2, 3]
Output : ['geeks', 'for', 'geeks']

Below are some Pythonic approaches to do the above task. 

Approach #1 : Naive(List comprehension) The first approach to find the desired elements is to use list comprehension. We traverse through ‘lst2’ and for each ith element, we output lst1[i]. 

Python3




# Python3 program to Find elements of a
# list by indices present in another list
 
def findElements(lst1, lst2):
    return [lst1[i] for i in lst2]
             
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))


Output:

[10, 30, 50]

Time complexity: O(n), where n is the length of lst2
Auxiliary space: O(m), where m is the length of the returned list.

Approach #2 : Using Python map() We can also use Python map() method where we apply lst1.__getitem__ function on lst2 which return lst1[i] for each element ‘i’ of lst2. 

Python3




# Python3 program to Find elements of a
# list by indices present in another list
 
def findElements(lst1, lst2):
    return list(map(lst1.__getitem__, lst2))
             
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))


Output:

[10, 30, 50]

Time complexity: O(n), where n is the length of lst2.
Auxiliary space: O(m), where m is the length of lst2.

Approach #3 : Using itemgetter() 

Python3




# Python3 program to Find elements of a
# list by indices present in another list
from operator import itemgetter
 
def findElements(lst1, lst2):
    return list((itemgetter(*lst2)(lst1)))
             
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))


Output:

[10, 30, 50]

Time complexity: O(m), where m is the length of the lst2 list. 
Auxiliary space: O(m+k), where k is the length of the returned list. 

Approach #4: Using numpy 

Python3




# Python3 program to Find elements of a
# list by indices present in another list
import numpy as np
 
def findElements(lst1, lst2):
    return list(np.array(lst1)[lst2])
             
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))


Output:

[10, 30, 50]

The time complexity of this program is O(n), where n is the length of lst2. 

The space complexity of this program is O(n), where n is the length of lst2.

Approach #6: Using a dictionary

This approach involves creating a dictionary that maps the indices in lst2 to their corresponding elements in lst1. Then, we can uselist comprehension to extract the values from the dictionary.

In this code, we first create a dictionary called index_map that maps the indices of lst1 to their corresponding elements. Then, we use a list comprehension to extract the values from index_map for the indices in lst2. Finally, we return the list of extracted values as the result.

Python3




def findElements(lst1, lst2):
    # Create a dictionary that maps indices in lst2 to their corresponding elements in lst1
    index_map = {index: element for index, element in enumerate(lst1)}
     
    # Use a list comprehension to extract the values from the dictionary
    return [index_map[index] for index in lst2]
 
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

[10, 30, 50]

Time complexity: O(n)
Auxiliary space: O(n)

Method#7: Using Recursive method.

Algorithm:

  1. Define a function findElements that takes in two lists lst1 and lst2, and an index idx (optional, default=0) and a list res (optional, default=[]).
  2. If idx is equal to the length of lst2, return res (base case).
  3. Get the element at the index lst2[idx] in lst1 and append it to res.
  4. Recursively call findElements with the updated idx (idx+1) and res.
  5. Return the final value of res after all recursive calls have finished.

Python3




def findElements(lst1, lst2, idx=0, res=[]):
    if idx == len(lst2):
        return res
    res.append(lst1[lst2[idx]])
    return findElements(lst1, lst2, idx+1, res)
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
res = findElements(lst1, lst2)
print(res)


Output

[10, 30, 50]

Time Complexity: O(n), where n is the length of lst2. We visit each element of lst2 exactly once, and the time taken to get the element at each index in lst1 is constant time. So the time complexity is proportional to the length of the input list lst2.

Auxiliary Space: O(n), where n is the length of lst2. This is because we need to store the list of elements in res, which can have a maximum length of n if all indices in lst2 are valid. Additionally, the recursive calls use up memory on the call stack, which can go up to a depth of n if all indices in lst2 are valid.



Previous Article
Next Article

Similar Reads

Python | Indices of sorted list of list elements
Sorting is a common construct and there have been many variations of it being discussed. But sometimes, we need to perform the sorting on the list of list and moreover just require to find the order in which element occurs before getting sorted. Let's find out how to get indices of sorted order in list of lists. Method #1 : Using List comprehension
6 min read
NumPy indices() Method | Create Array of Indices
The indices() method returns an array representing the indices of a grid. It computes an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis. Example C/C++ Code import numpy as np gfg = np.indices((2, 3)) print (gfg) Output : [[[0 0 0] [1 1 1]] [[0 1 2] [0 1 2]]]Syntax numpy.indices(dimensions, dtype, sp
2 min read
Python | Group elements at same indices in a multi-list
Flattening a 2D list to one is a common problem that is faced in many domains. But sometimes we require to pair elements at specific indices as one, so that elements at respective indices are together. This problem is not common but still having a solution to it helps. Let's discuss certain ways to pair elements at specific indices. Method #1 : Usi
9 min read
Python | Indices of N largest elements in list
Sometimes, while working with Python lists, we can have a problem in which we wish to find N largest elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let's discuss a certain way to find indices of N largest elements in the list. Meth
5 min read
Python - Indices of atmost K elements in list
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of duplicate numbers. Let’s discuss certain ways in which
7 min read
Python - Get Indices of Even Elements from list
Sometimes, while working with Python lists, we can have a problem in which we wish to find Even elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let us discuss certain ways to find indices of Even elements. Method #1: Using loop This
8 min read
Python - Remove elements at Indices in List
Given List, remove all the elements present in the indices list in Python. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5] Output : [5, 6, 7, 2, 10] Explanation : 3, 6, and 1 has been removed. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2] Output : [5, 6, 7, 8, 1, 2, 10] Explanation : 3 has been removed. In this a
7 min read
Python | Indices list of matching element from other list
Sometimes, while working with Python list, we have a problem in which we have to search for an element in list. But this can be extended to a list and need to find the exact places where elements occur in another list. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + count() This is the brute method to perform
7 min read
Python program to get the indices of each element of one list in another list
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],
7 min read
Python - Find the indices for k Smallest elements
Sometimes, while working with Python lists, we can have a problem in which we wish to find the indices for K smallest elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss a certain way to find indices of K smallest elements
8 min read
Practice Tags :