Monday, November 18, 2024
Google search engine
HomeLanguagesPython | Find elements of a list by indices

Python | Find elements of a list by indices

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', 'Lazyroar', 'for', 'Lazyroar']
        lst2 = [1, 2, 3]
Output : ['Lazyroar', 'for', 'Lazyroar']

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.

RELATED ARTICLES

Most Popular

Recent Comments