How to check if item exists in a tuple in python

Many times it is required to test if an element is present in a python tuple or to find a value in tuple such as while validating user input from among a list of pre-defined choices.
In this article, you will learn 2 different ways in which you can check whether an item exists in a tuple.

Method 1: Using in operator
This is the shortest method to test the presence of an element in tuple. Place in operator between the element and tuple, the result will be True if the element is found in tuple, else it will be False. Example,

# declare a tuple
t = (12,9,10,13)
# value to find
element = 9
if element in t:
    print(element,"exists in tuple")
    print(element,"does not exist in tuple")

Above python program will check if the given number is present in a tuple or not. Output will be

9 exists in tuple

Method 2: Using loop
Iterate over the tuple using a for loop and compare each element with the value to find in tuple. Example,

# declare tuple
t = (12,9,10,13)
# item to find
element = 11
found = False
# iterate over tuple
for loop_element in t:
    # compare tuple element with item to check
    if loop_element == t:
        found = True
        # terminate loop if item is found
        found = False

if found:
    print(element,"exists in tuple")
    print(element,"does not exist in tuple")

Above program uses a loop to iterate over tuple elements. In every iteration, it compares the value that needs to be searched in the tuple with the current tuple element.
If both values match, it sets a boolean flag and breaks the loop since there is no point in continuing the loop. After the loop, this flag is checked to determine if the value was found in tuple.
Output of this program is

11 does not exist in tuple

Do not forget to hit the clap if the post was helpful.


Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.
%d bloggers like this: