Joan Venge
Joan Venge

Reputation: 331470

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

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.

Upvotes: 37

Views: 132227

Answers (5)

Roberto
Roberto

Reputation: 1

Try this:

fruits = ['peach', 'blueberry', 'raspberry', 'apple', 'orange',  'lemon', 'banana']
first, second, *others = fruits

print(others) # ['raspberry', 'apple', 'orange', 'lemon', 'banana']

Upvotes: 0

HasanAlyazidi
HasanAlyazidi

Reputation: 619

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

Upvotes: 2

magusvox
magusvox

Reputation: 119

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()

Upvotes: 11

Eitan Bendersky
Eitan Bendersky

Reputation: 67

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

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


simha()

Upvotes: 1

Lennart Regebro
Lennart Regebro

Reputation: 172377

You use in.

if element in thetuple:
    #whatever you want to do.

Upvotes: 89

Related Questions