Write a Python Program to Check if a Specified Element Presents in a Tuple of Tuples

Hi, in this article lets take a nested tuple and find an element if its present in the nested tuple or not.

Tuple of tuples (aka Nested Tuple) is a data structure containing individual tuple, inside a tuple. you can refer the Phase 1 example it contains 6 tuples having integers, inside another tuple.

There are two variants of this program lets look into both first is using general method for and if and next is any() method.

 

tuple of tuples

 

 

Python Program to Check if a Specified Element Presents in a Tuple of Tuples

Phase 1 :

nested_tuple = ((56,), (34, 67, 90), (99, 78), (45, 33), (91,), (123, 45, 11, 22, 89))

 

Phase 2 :  Ask user to enter a element

element = int(input("Please enter element to search : "))


Phase 3 : Check if element is in tuple using for and if loop.

for single_tuple in nested_tuple:
    if element in single_tuple:
        print("Element Found !")
        exit(0)
else:
    print("Element not found")

 

Phase 3 : Can also be re written as below using four line code. any() function returns True if any one of the iterator is true else false.

if any(element in item for item in my_tuple):
    print("Element found !")
else:
    print("Element not found !")


Final program using for and if statement : 

nested_tuple = ((56,), (34, 67, 90), (99, 78), (45, 33), (91,), (123, 45, 11, 22, 89))

element = int(input("Please enter element to search : "))

for single_tuple in nested_tuple:
    if element in single_tuple:
        print("Element Found !")
        exit(0)
else:
    print("Element not found")

 

Final program using any() Function: 

nested_tuple = ((56,), (34, 67, 90), (99, 78), (45, 33), (91,), (123, 45, 11, 22, 89))

element = int(input("Please enter element to search : "))

if any(element in item for item in my_tuple):
    print("Element found !")
else:
    print("Element not found !")

 

Keywords : Write a Python Program to Check if a Specified Element Presents in a Tuple of Tuples

Post a Comment

0 Comments