Kosig Kosig - 7 months ago 142
Python Question

In Python, how to compare two lists and get all indices of matches?

This is probably a simple question that I am just missing but I have two lists containing strings and I want to "bounce" one, element by element, against the other returning the index of the matches. I expect there to be multiple matches and want all of the indices. I know that list.index() gets the first and you can easily get the last. For example:

list1 = ['AS144','401M','31TP01']

list2 = ['HDE342','114','M9553','AS144','AS144','401M']


Then I would iterate through list1 comparing to list2 and output:

[0,0,0,1,1,0] , [3,4]
or etc for the first iteration

[0,0,0,0,0,1] , [6]
for second

and
[0,0,0,0,0,0]
or
[]
for third

EDIT:
Sorry for any confusion. I would like to get the results in a way such that I can then use them like this- I have a third list lets call list3 and I would like to get the values from that list in the indices that are outputed. ie
list3[previousindexoutput]=list of cooresponding values

Answer
[([int(item1 == item2) for item2 in list2], [n for n, item2 in enumerate(list2) if item1 == item2]) for item1 in list1]