Python | Replace elements in second list with index of same element in first list
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 InitializationInput1 = ['cut', 'god', 'pass']Input2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']# List InitializationOutput = []# Using iterationfor x in Input2: for y in Input1: if x == y: Output.append(Input1.index(y))# Printing outputprint("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 #2: Using List comprehension
Python3
# Python code to replace every element# in second list with index of first element.# List initializationInput1 = ['cut', 'god', 'pass']# using enumeratetemp = {y:x for x, y in enumerate(Input1)}# List initializationInput2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']# Using list comprehensionOutput = [temp.get(elem) for elem in Input2]# Printing outputprint("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 #3 : Using map
Python3
# Python code to replace every element# in second list with index of first element.# List initializationInput1 = ['cut', 'god', 'pass']# List initializationInput2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']elem = {k: i for i, k in enumerate(Input1)}Output = list(map(elem.get, Input2))# Printing outputprint("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]



