Contents
Check if Item Exists in Python Tuple
Python Tuple is a collection of items. You can check if an item is present in the Tuple or not.
There are multiple ways to check if an item is present or not in a Tuple, and we shall discuss some of them in this tutorial.
Some of those methods are:
- Use if..not.
- Iterate through tuple items and check.
Example 1: if..not to check if Item is present in Tuple
Python Program
tuple1 = (5, 3, 2, 8, 4, 4, 6, 2)
#check if element is present
if 8 in tuple1:
print('8 is in the tuple', tuple1)
else:
print('8 is not in the tuple', tuple1)
if 9 in tuple1:
print('9 is in the tuple', tuple1)
else:
print('9 is not in the tuple', tuple1)
Run Output
8 is in the tuple (5, 3, 2, 8, 4, 4, 6, 2)
9 is not in the tuple (5, 3, 2, 8, 4, 4, 6, 2)
Example 2: Use for loop to check if Item is present in Tuple
In this example program, we take a tuple and the item to check if it is present in the tuple. Then we shall use for loop to iterate over each item in the tuple and compare this item with the value we are trying to check. If there is a match found, we shall set the boolean value for the variable and come out of the loop.
Python Program
tuple1 = (5, 3, 2, 8, 4, 4, 6, 2)
check_item = 8
is_item_present = False
for item in tuple1:
if item==check_item:
is_item_present = True
break
print('Is', check_item,'Present? ', is_item_present)
Run Output
Is 8 Present? True
This method is only for demonstrating an other way of solving the problem. The method used in first example is recommended to use in your application.
Summary
In this tutorial of Python Examples, we learned how to check if an item is present or not in Python Tuple.