Home > Mobile >  How to check if a value exists in one of several lists
How to check if a value exists in one of several lists

Time:04-12

I have the following code:

answer = int(input("input number in range 1-6: "))
yes = [1, 2, 3]
no = [4, 5, 6]
while answer not in yes:
    print("what?")
    answer = int(input())
else:
    if answer in no:
        print("no")
    elif answer in yes:
        print("yes")

I want the while loop to terminate if the number is in either the yes list or the no list. How can I include the second list in the while loop condition correctly?

CodePudding user response:

You can concatenate the lists using the addition operator:

while answer not in yes   no:

CodePudding user response:

You could also use and:

while answer not in yes and answer not in no:

Also, there are other ways you can concatenate yes and no:

  • while answer not in [*yes, *no]:
  • You could add import itertools and check both the lists with while answer not in itertools.chain(yes, no):
  • while answer not in [j for i in zip(yes, no) for j in i]:
  • Related