Search code examples
pythonlistwhile-loopbreakraw-input

How to compare two lists with a while loop


I'm trying to make a script that takes in an answer and appends it to a new list, then checks to see if the new list is the same as the other list. When these lists are the same, the while loop should break.

NOTE: Each question should not repeat.

Here's my code:

import random 

questions = ['a','b','c','d','e']

answered_q = []

while len(answered_q) < len(questions):
    question = random.choice(questions)
    answered_q.append(question)
    raw_input = str(input(question + ": "))
    if sorted(questions) == sorted(answered_q):
        break

When executed I am still getting random questions but the code does not break when the lists have the same contents.

output :

['b','c','b,'d','d']

If anyone can help it would be great! Thanks in advance!


Solution

  • I think what you really want to do is only append to your new list if the element to be added isn't already in there, so add a check for that.

    while len(answered_q) < len(questions):
        question = random.choice(questions)
        if question not in answered_q:
            answered_q.append(question)
            raw_input = str(input(question + ": "))
            if sorted(questions) == sorted(answered_q):
                break
    

    Of course, under this scheme, the loop should end even without the last if-statement because the length of the two lists will be equal by the time the two sorted lists will be equal.