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.
Add a comment
|
3 Answers
You use in
.
if element in thetuple:
#whatever you want to do.
-
Thanks, for multiple elements should I do if a in tuple and b in tuple: ? Jul 29, 2013 at 9:20
-
Yes. If you have a lot of elements you might consider using
set
s instead, where you can do union, difference and intersection operations. Jul 29, 2013 at 9:23 -
Thanks, actually the API I am using is returning a tuple, that's why I was using that. Should I convert it to a set? Jul 29, 2013 at 9:23
-
-
Thanks 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. Jul 29, 2013 at 9:29
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()
-
Hi 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– DaniloSep 1, 2019 at 23:59 -
1its 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– magusvoxSep 2, 2019 at 22:39
-
That's not good solution, since it will return true even if the tuple contains "sword". Aug 2 at 19:22
Be careful with that: return Oops. use Set: d= {...}
def simha():
d = ('this_is_valid')
b = 'valid'
if b in d:
print("Oops!!!!!")
simha()
-
3tuples 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.– YEp dJul 4, 2021 at 3:24