List of index where corresponding elements of two lists are same

Viewed 795

I want to compare two different lists and return the indexes of similar stings.

For example, if I have two lists like:

grades = ['A', 'B', 'A', 'E', 'D']
scored = ['A', 'B', 'F', 'F', 'D']

My expected output is:

 [0, 1, 4] #The  indexes of similar strings in both lists

However this is the result I am getting at the moment:

[0, 1, 2, 4] #Problem: The 2nd index being counted again

I have tried coding using using two approaches.

First Approach:

def markGrades(grades, scored):
    indices = [i for i, item in enumerate(grades) if item in scored]
    return indices

Second Approach:

def markGrades(grades, scored):
    indices = []
    for i, item in enumerate(grades):
         if i in scored and i not in indices:
         indices.append(i)
    return indices

The second approach returns correct strings but not the indexes.

3 Answers

You can use enumerate along with zip in list comprehension to achieve this as:

>>> grades = ['A', 'B', 'A', 'E', 'D']
>>> scored = ['A', 'B', 'F', 'F', 'D']

>>> [i for i, (g, s) in enumerate(zip(grades, scored)) if g==s]
[0, 1, 4]

Issue with your code is that you are not comparing the elements at the same index. Instead via using in you are checking whether elements of one list are present in another list or not.

Because 'A' at index 2 of grades is present in scored list. You are getting index 2 in your resultant list.

Your logic fails in that it doesn't check whether the elements are in the same position, merely that the grades element appears somewhere in scored. If you simply check corresponding elements, you can do this simply.

Using your second approach:

for i, item in enumerate(grades):
    if item == scored[i]:
        indices.append(i)

The solution that Anonymous gives is what I was about to add as the "Pythonic" way to solve the problem.

You can access the two lists in pairs (to avoid the over-generalization of finding a match anywhere in the other array) with zip

grades = ['A', 'B', 'A', 'E', 'D']
scored = ['A', 'B', 'F', 'F', 'D']

matches = []
for ix, (gr, sc) in enumerate(zip(grades,scored)):
    if gr == sc:
        matches.append(ix)

or more compactly with list comprehension, if that suits your purpose

matches = [ix for ix, (gr, sc) in enumerate(zip(grades,scored)) if gr == sc]
Related