Open In App

Python | Replace elements in second list with index of same element in first list

Last Updated : 16 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Share
2 Likes
Like
Report

Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list.

Method #1: Using Iteration 


Output: 
initial 2 list are
['cut', 'god', 'pass'] 
 ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Second list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]

 

Time Complexity : O(n*m)

Auxiliary Space : O(n+m), where n is length of Input1 list and m is length of Input2 list.

  
Method #2: Using List comprehension 
 


Output: 
initial 2 list are
['cut', 'god', 'pass'] 
 ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Second list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]

 

Time Complexity: O(n)
Auxiliary Space: O(n)

  Method #3 : Using map 


Output: 
initial 2 list are
['cut', 'god', 'pass'] 
 ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Second list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]

 

Method #4: Using dictionary comprehension

This method uses a dictionary to store the indices of the elements in input1. It then uses a list comprehension to iterate through input2 and replace each element with its index in the dictionary. This is a simple and efficient way to solve the task.


Output
Input1: ['cut', 'god', 'pass']
Input2: ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Output: [1, 0, 0, 0, 1, 2, 0, 2]

Time complexity: O(n) where n is the length of input2
Auxiliary Space: O(n) to store the dictionary and output list

Method #5: Using Regular expressions


Output
initial 2 list are
['cut', 'god', 'pass'] 
 ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Second list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]

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

Method #6: Using enumerate() function

Use the built-in enumerate() function to iterate through the elements of Input2 along with their indices. Then, for each element in Input2, we can check if it exists in Input1 using the in operator. If it exists, we can append the index of the matching element in Input1 to the Output list.


Output
initial 2 list are
['cut', 'god', 'pass'] 
 ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Second list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]

Time Complexity: O(n^2), where n is the length of Input2.
Auxiliary Space: O(1), as we are only using the Output list to store the indices.


Next Article
Practice Tags :

Similar Reads