Find indexes of common items in two python lists

Question:

I have two lists in python list_A and list_B and I want to find the common item they share. My code to do so is the following:

both = []
for i in list_A:
    for j in list_B:
        if i == j:
            both.append(i)

The list common in the end contains the common items. However, I want also to return the indexes of those elements in the initial two lists. How can I do so?

Asked By: konstantin

||

Answers:

Instead of iterating through the list, access elements by index:

both = []
for i in range(len(list_A)):
    for j in range(len(list_B)):
        if list_A[i] == list_B[j]:
            both.append((i,j))

Here i and j will take integer values and you can check values in list_A and list_B by index.

Answered By: RohithS98

It is advised in python that you avoid as much as possible to use for loops if better methods are available. You can efficiently find the common elements in the two lists by using python set as follows

both = set(list_A).intersection(list_B)

Then you can find the indices using the build-in index method

indices_A = [list_A.index(x) for x in both]
indices_B = [list_B.index(x) for x in both]
Answered By: kosnik

You can also get common elements and their indexes with numpy.intersect1d()

common_elements, a_indexes, b_indexes = np.intersect1d(a, b, return_indices=True)
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.