Search code examples
pythonlistnested-loops

python: compare lists in a sequence using nested for loops


so I have two lists where I compare a person's answers to the correct answers:

correct_answers = ['A', 'C', 'A', 'B', 'D']
user_answers = ['B', 'A', 'C', 'B', 'D']

I need to compare the two of them (without using sets, if that's even possible) and keep track of how many of the person's answers are wrong - in this case, 3

I tried using the following for loops to count how many were correct:

correct = 0

for i in correct_answers:
    for j in user_answers:
        if i == j:
            correct += 1

print(correct)

but this doesn't work and I'm not sure what I need to change to make it work.


Solution

  • The less pythonic, more generic (and readable) solution is pretty simple too.

    correct_answers = ['A', 'C', 'A', 'B', 'D']
    user_answers = ['B', 'A', 'C', 'B', 'D']
    
    incorrect = 0
    for i in range(len(correct_answers)):
        if correct_answers[i] != user_answers[i]:
            incorrect += 1
    

    This assumes your lists are the same length. If you need to validate that, you can do it before running this code.

    EDIT: The following code does the same thing, provided you are familiar with zip

    correct_answers = ['A', 'C', 'A', 'B', 'D']
    user_answers = ['B', 'A', 'C', 'B', 'D']
    
    incorrect = 0
    for answer_tuple in zip(correct_answers, user_answers):
        if answer_tuple[0] != answer_tuple[1]:
            incorrect += 1