Write a Python Program to Check whether the given item exists in a Tuple or not. We use the in operator to find the item that exists in a tuple.
# Check Element Presnet in Tuple numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16) print("Tuple Items = ", numTuple) number = int(input("Enter Tuple Item to Find = ")) result = number in numTuple print("Does our numTuple Contains the ", number, "? ", result)
Although the above example returns the True or False, we need a meaningful message. So, we used the If statement and in operator (if number in numTuple) to print a different message if item exists in Tuple.
# Check Element Presnet in Tuple numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16) print("Tuple Items = ", numTuple) number = int(input("Enter Tuple Item to Find = ")) if number in numTuple: print(number, " is in the numTuple") else: print("Sorry! We haven't found ", number, " in numTuple")
Tuple Items = (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 22
22 is in the numTuple
>>>
Tuple Items = (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 124
Sorry! We haven't found 124 in numTuple
>>>
Python Program to Check Item exists in Tuple using For Loop
In this Python example, we used the if statement (if val == number) to check each tuple item against the given number. If true, the result becomes True, and break will exist the compiler from for loop.
# Check Element Presnet in Tuple numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16) print("Tuple Items = ", numTuple) number = int(input("Enter Tuple Item to Find = ")) result = False for val in numTuple: if val == number: result = True break print("Does our numTuple Contains the ", number, "? ", result)
Tuple Items = (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 16
Does our numTuple Contains the 16 ? True