How to check if a tuple contains an element in Python?
95,529
Solution 1
You use in
.
if element in thetuple:
#whatever you want to do.
Solution 2
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()
Related videos on Youtube
Comments
-
Joan Venge over 3 years
I tried to find the available methods but couldn't find it. There is no
contains
. Should I useindex
? I just want to know if the item exists, don't need the index of it. -
Joan Venge over 10 yearsThanks, for multiple elements should I do if a in tuple and b in tuple: ?
-
Lennart Regebro over 10 yearsYes. If you have a lot of elements you might consider using
set
s instead, where you can do union, difference and intersection operations. -
Joan Venge over 10 yearsThanks, actually the API I am using is returning a tuple, that's why I was using that. Should I convert it to a set?
-
Lennart Regebro over 10 years@JoanVenge: If you want it to be a set, yes.
-
Joan Venge over 10 yearsThanks will do. I just didn't want to change the data types too much because it's gonna get called 10000s of times every frame.
-
Lennart Regebro over 10 years@JoanVenge: Yes, making a
set
of atuple
is a heavy operation, so doing that 10.0000 times is generally not desirable. You have a specific situation and a specific problem, but you ask very generic questions. The answers you get will not be very useful. -
Joan Venge over 10 yearsOk thanks, I will just use
in
twice because it's only 2 checks. I just didn't want to make it very messy. -
Lennart Regebro over 10 yearsThen using a set is not useful.
-
Danilo over 4 yearsHi new contributor. Your answer was similar as accepted answer, but you should know that keyword in is same as
__contains__
overloaded operator on class. So when original poster said that there was no__contains__
he/she meant that it wasn't possible to use in keyword on data set. As you can see string class has that operator implemented so your answer is ok. Keep going! :D -
magusvox over 4 yearsits true, i was not seen the specification in the question. I was looking to solve my problem (a 'str' situation) and I found that the question wasnt about it only after the answer haha
-
YEp d almost 3 yearstuples are only created in python if you use the notation
(element,)
. The comma is very important. If there is no comma, python treats it like an expression to evaluate.