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.
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") else: 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 break else: found = False if found: print(element,"exists in tuple") else: 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