Check if a specific item exists in Tuple


Check if a specific item exists in 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:

  1. Use if..not.
  2. Iterate through tuple items and check.

Examples

1. Check if item '8' is present in Tuple using for..in

Python Program

tuple1 = (5, 3, 2, 8, 4, 4, 6, 2)

# Check if item 8 is present in the tuple
if 8 in tuple1:
    print('8 is in the tuple', tuple1)
else:
    print('8 is not in the tuple', tuple1)

Output

8 is in the tuple (5, 3, 2, 8, 4, 4, 6, 2)

2. Check if item 'apple' is present in Tuple using For loop

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 = ('apple', 'banana', 'cherry')

search_item = 'apple'
is_item_present = False

for item in tuple1:
    if item==search_item:
        is_item_present = True
        break
        
if is_item_present:
    print(f'{search_item} is present in the tuple.')
else:
    print(f'{search_item} is not present in the tuple.') 

Output

apple is present in the tuple.

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.