Search code examples
pythonpython-3.xstringlistenumerate

List of index where corresponding elements of two lists are same


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.


Solution

  • 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.