How to check if a tuple contains an element in Python?

Question:

I tried to find the available methods but couldn’t find it. There is no contains. Should I use index? I just want to know if the item exists, don’t need the index of it.

Asked By: Joan Venge

||

Answers:

You use in.

if element in thetuple:
    #whatever you want to do.
Answered By: Lennart Regebro

Be careful with that:
return Oops.
use Set: d= {…}

def simha():
    d = ('this_is_valid')
    b = 'valid'
    if b in d:
        print("Oops!!!!!")


simha()
Answered By: Eitan Bendersky
if "word" in str(tuple):
# You can convert the tuple to str too

i has the same problem and only worked to me after the convert str()

Answered By: magusvox

Use as follows: variable_name in tuple

animals = ('Dog', 'Elephant', 'Fox')

animal_name = 'Fox'

Check if an x is in animals tuple:

if animal_name in animals :
    # Fox is existing in animals

Check if an x is NOT in animals tuple:

if not animal_name in animals :
    # Fox is not existing in animals
Answered By: HasanAlyazidi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.