Search code examples
pythonlistsumzipincrement

Comparing two Lists using Zip function in Python


I am comparing two lists together and if they match I want to increment a counter. Right now the counter is saying 0 each time I print it out even though there should be some matches. Both lists have data within them as well because I can print them out. Below is the code that I am using to find a match in the lists and increment if they do match. What could be going wrong?

numCorrect = sum(1 for a, b in zip(trueLabels, predLabels) if a == b)

Any advice helps, Thanks


Solution

  • Your code works well:

    trueLabels = [1, 2, 3, 4, 5]
    predLabels = [1, 2, 4, 4, 5]
    
    numCorrect = sum(1 for a, b in zip(trueLabels, predLabels) if a == b)
    print(numCorrect)
    # 4
    

    You may have shifted indices in your list(s).