Skip to content
Advertisement

Check to see if two lists have the same value at the same index, if so return the index. If not return -1

So basically I am trying to compare two lists to see if they hold the same value at the same index at any point. If they do I return the index, if they do not, I return -1.

When I had first done this as a test I was having no issues however adding in the text has made it more difficult and my main issue is with the if else statement. I seem to be able to only get one message to work, either yes or no, not both based on the case.

Advertisement

Answer

I think a cleaner answer uses the built-in enumerate and zip functions:

Dlist = [17,13,10,6,2]
Ilist = [5,9,10,15,18]

def seqsearch(DS,IS):
    for idx, (d, s) in enumerate(zip(DS, IS)):
        if d == s:
            return f"Yes! Found at index = {idx}"

    return "No!n-1"


print(seqsearch(Dlist,Ilist))

It’s unclear whether you want to return just the first index, or all the indices with matching elements. In either case, it is probably better if you just return the desired value and then add any formatting and print statements outside of the function’s scope.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement