Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 804
Joan Venge Avatar asked Jul 29 '13 09:07

Joan Venge


People also ask

How do you check if an element exists in a tuple?

Method #1: Using any() any function is used to perform this task. It just tests one by one if the element is present as the tuple element. If the element is present, true is returned else false is returned.

How do you check that tuple A contains all elements of tuple B?

You can use set. issubset or set. issuperset to check if every element in one tuple or list is in other.

What keyword will be used to check if the value exist in a tuple?

1. Tuple Membership Test. We can test if an item exists in a tuple or not, using the keyword in .


3 Answers

You use in.

if element in thetuple:
    #whatever you want to do.
like image 72
Lennart Regebro Avatar answered Oct 06 '22 06:10

Lennart Regebro


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

like image 8
magusvox Avatar answered Oct 06 '22 06:10

magusvox


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

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


simha()
like image 1
Eitan Bendersky Avatar answered Oct 06 '22 06:10

Eitan Bendersky