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

Personally I’d start with:

matches = [item for item in list1 if item in list2]

Leave a Comment