Home > Enterprise >  Python, alternative to not in list
Python, alternative to not in list

Time:03-10

I've seen lots of questions regarding 'not in list', but few alternatives to the solution I need or issue I have which i thought would be the normal use case?

list = [1, 2, 3, 4, 5, 6] 
while list:
        q1 = int(input("Enter number: "))
        if q1 in list:
            list.remove(q1)
            print("match")
        elif q1 not in list:
          print("No match")
else:
  print("end")

I understand the logic is basically saying If true = true then true which doesn't work, but you also can't say "if q1 in not list:" either. So if you want to check if q1 is not in list, then how do you do that?


Well, maybe I just figured this out.

list = [1, 2, 3, 4, 5, 6] 
while list:
        q1 = int(input("Enter number: "))
        if q1 in list:
            list.remove(q1)
            print("match")
        elif not q1 in list:
          print("No match")
else:
  print("end")

Seems to do exactly what I want and what I've seen other people trying to do. I hope this is correct.

however, now I want to do list1 and list2 but:

        elif not q1 in list1 and list2:
          print("No match")

does not work.

CodePudding user response:

You can simplify your code like this:

listt = [1, 2, 3, 4, 5, 6] 
while listt:
    q1 = int(input("Enter number: "))
    if q1 in listt:
        listt.remove(q1)
        print("match")
    else:
        print("No match")
print("end")

Or you could do:

listt = [1, 2, 3, 4, 5, 6] 
while listt:
    q1 = int(input("Enter number: "))
    if not q1 in listt:
        print("No match")
    else:
        print("Match")
        listt.remove(q1)

CodePudding user response:

you can use try and except as alternative solution

list = [1, 2, 3, 4, 5, 6] 
while list:
        q1 = int(input("Enter number: "))
        try:
            list.remove(q1)
            print("match")
        except ValueError:
            print("No match")
  • Related