I am comparing two lists in Python.
list1
is a superset of list2
.
For the elements of list1
, I want their index in list2
(if present).
Here are two examples.
list1 = ['a','b','c','d']
list2 = ['a','b']
The solution should produce [0, 1]
.
list1 = ['a','b','c','d']
list2 = ['b','a']
The solution should produce [1, 0]
.
I attempted the following code, but it only works for the first example.
list1 = ['a','b','c','d']
list2 = ['a','b']
pairwise = zip(list1,list2)
matched_index = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]
This works. However, for the second set of sample data I get the wrong output []
instead of the expected output [1, 0]
.
list1 = ['a','b','c','d']
list2 = ['b','a']
pairwise = zip (list1,list2)
matched_index = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]
print(matched_index) # prints []
Please suggest the way forward.