Search code examples
pythonpython-3.xcontains

How to use Python 'in' operator to check my list/tuple contains each of the integers 0, 1, 2?


How do I use the Python in operator to check my list/tuple sltn contains each of the integers 0, 1, and 2?

I tried the following, why are they both wrong:

# Approach 1
if ("0","1","2") in sltn:
     kwd1 = True

# Approach 2
if any(item in sltn for item in ("0", "1", "2")):
     kwd1 = True

Update: why did I have to convert ("0", "1", "2") into either the tuple (1, 2, 3)? or the list [1, 2, 3]?


Solution

  • if ("0","1","2") in sltn
    

    You are trying to check whether the sltn list contains the tuple ("0","1","2"), which it does not. (It contains 3 integers)

    But you can get it done using #all() :

    sltn = [1, 2, 3] # list
    tab = ("1", "2", "3") # tuple
    
    print(all(int(el) in sltn for el in tab)) # True