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

Share:
95,529

Related videos on Youtube

Joan Venge
Author by

Joan Venge

Professional hitman.

Updated on September 02, 2020

Comments

  • Joan Venge
    Joan Venge over 3 years

    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.

  • Joan Venge
    Joan Venge over 10 years
    Thanks, for multiple elements should I do if a in tuple and b in tuple: ?
  • Lennart Regebro
    Lennart Regebro over 10 years
    Yes. If you have a lot of elements you might consider using sets instead, where you can do union, difference and intersection operations.
  • Joan Venge
    Joan Venge over 10 years
    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?
  • Lennart Regebro
    Lennart Regebro over 10 years
    @JoanVenge: If you want it to be a set, yes.
  • Joan Venge
    Joan Venge over 10 years
    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.
  • Lennart Regebro
    Lennart Regebro over 10 years
    @JoanVenge: Yes, making a set of a tuple 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
    Joan Venge over 10 years
    Ok 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
    Lennart Regebro over 10 years
    Then using a set is not useful.
  • Danilo
    Danilo over 4 years
    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
  • magusvox
    magusvox over 4 years
    its 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
    YEp d almost 3 years
    tuples 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.