Python | Replace elements in second list with index of same element in first list
Last Updated :
16 Mar, 2023
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
Python3
# Python code to replace every element
# in second list with index of first element.
# List Initialization
Input1 = ['cut', 'god', 'pass']
Input2 = ['god', 'cut', 'cut', 'cut',
'god', 'pass', 'cut', 'pass']
# List Initialization
Output = []
# Using iteration
for x in Input2:
for y in Input1:
if x == y:
Output.append(Input1.index(y))
# Printing output
print("initial 2 list are")
print(Input1, "\n", Input2)
print("Second list after replacement is:", Output)
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
Python3
# Python code to replace every element
# in second list with index of first element.
# List initialization
Input1 = ['cut', 'god', 'pass']
# using enumerate
temp = {y:x for x, y in enumerate(Input1)}
# List initialization
Input2 = ['god', 'cut', 'cut', 'cut',
'god', 'pass', 'cut', 'pass']
# Using list comprehension
Output = [temp.get(elem) for elem in Input2]
# Printing output
print("initial 2 list are")
print(Input1, "\n", Input2)
print("Second list after replacement is:", Output)
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
Python3
# Python code to replace every element
# in second list with index of first element.
# List initialization
Input1 = ['cut', 'god', 'pass']
# List initialization
Input2 = ['god', 'cut', 'cut', 'cut',
'god', 'pass', 'cut', 'pass']
elem = {k: i for i, k in enumerate(Input1)}
Output = list(map(elem.get, Input2))
# Printing output
print("initial 2 list are")
print(Input1, "\n", Input2)
print("Second list after replacement is:", Output)
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.
Python3
def replace_elements(input1, input2):
# Create a dictionary with keys from input1 and values as the indices
dictionary = {input1[i]: i for i in range(len(input1))}
# Use a list comprehension to replace each element in input2 with its corresponding index in the dictionary
return [dictionary[elem] for elem in input2]
#initialization
Input1 = ['cut', 'god', 'pass']
Input2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Output = replace_elements(Input1, Input2)
#printing result
print(f"Input1: {Input1}")
print(f"Input2: {Input2}")
print(f"Output: {Output}")
#This code is contributed by Edula Vinay Kumar Reddy
OutputInput1: ['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
Python3
import re
Input1 = ['cut', 'god', 'pass']
Input2 = ['god', 'cut', 'cut', 'cut',
'god', 'pass', 'cut', 'pass']
# Compile a regular expression pattern to match elements in Input1
pattern = re.compile("|".join(Input1))
# Use the re.finditer function to find all matches in Input2
matches = [m.group() for m in re.finditer(pattern, " ".join(Input2))]
# Replace elements in Input2 with their indices
Output = [Input1.index(x) for x in matches]
# Printing output
print("initial 2 list are")
print(Input1, "\n", Input2)
print("Second list after replacement is:", Output)
#This code is contributed by Vinay Pinjala.
Outputinitial 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.
Python3
# Python code to replace every element
# in second list with index of first element.
# List Initialization
Input1 = ['cut', 'god', 'pass']
Input2 = ['god', 'cut', 'cut', 'cut',
'god', 'pass', 'cut', 'pass']
# List Initialization
Output = []
# Using enumerate() function
for i, x in enumerate(Input2):
if x in Input1:
Output.append(Input1.index(x))
# Printing output
print("initial 2 list are")
print(Input1, "\n", Input2)
print("Second list after replacement is:", Output)
Outputinitial 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.
Similar Reads
Replace index elements with elements in Other List-Python
The task of replacing index elements with elements from another list involves mapping the indices from one list to the corresponding elements in a second list. For each index in the first list, the element at that index is retrieved from the second list and stored in a new result list. For example,
4 min read
Python | Sorting list of lists with similar list elements
Sorting has always been a key operation that is performed for many applications and also as a subproblem to many problems. Many variations and techniques have been discussed and their knowledge can be useful to have while programming. This article discusses the sorting of lists containing a list. Le
5 min read
Python - Rearrange elements second index greater than first
Given 2 lists, for a given index, 2nd list element is always larger than first, and if not, we rearrange it. Input : test_list1 = [36, 38, 40, 132], test_list2 = [35, 37, 39, 41, 133] Output : [37, 39, 41, 133] Explanation : Each element in result list is greater than its index counterpart of 1st li
3 min read
Python - Pair elements with Rear element in Matrix Row
Sometimes, while working with data, we can have a problem in which we need to pair each element in container to a specific index element, like rear element. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using lis
7 min read
Python | Convert column to separate elements in list of lists
There are instances in which we might require to extract a particular column of a Matrix and assign its each value as separate entity in list and this generally has a utility in Machine Learning domain. Let's discuss certain ways in which this action can be performed.Method #1 : Using list slicing a
4 min read
Python | Find common elements in list of lists
The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be
6 min read
Python program to interchange first and last elements in a list
Given a list, write a Python program to swap the first and last element of the list using Python.Examples: The last element of the list can be referred to as a list[-1]. Therefore, we can simply swap list[0] with list[-1].Python# Initialize a list my_list = [1, 2, 3, 4, 5] # Interchange first and la
5 min read
Python | Replace list elements with its ordinal number
Given a list of lists, write a Python program to replace the values in the inner lists with their ordinal values. Examples:Input : [[1, 2, 3], [ 4, 5, 6], [ 7, 8, 9, 10]]Output : [[0, 0, 0], [1, 1, 1], [2, 2, 2, 2]]Input : [['a'], [ 'd', 'e', 'b', 't'], [ 'x', 'l']]Output : [[0], [1, 1, 1, 1], [2, 2
5 min read
Python - Filter unequal elements of two lists corresponding same index
Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are unequal and have similar index. This kind of problem can come in many domains. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using
5 min read
Python | Remove given element from list of lists
The deletion of elementary elements from list has been dealt with many times, but sometimes rather than having just a one list, we have list of list where we need to perform this particular task. Having shorthands to perform this particular task can help. Let's discuss certain ways to perform this p
6 min read