Python – Test Similar Data Type in Tuple

Sometimes, while working with Python tuples, we can have a problem in which we need to test if all the elements in tuple have same data type. This kind of problem can have application across all domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = (5, 6, 7, 3, "Gfg")
Output : False

Input : test_tuple = (2, 3)
Output : True

Method #1 : Using loop + isinstance()
The combination of above functions can be used to solve this problem. In this, we perform the checking of data types using isinstance() and iteration is done as brute force way to account for all the elements.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Test Similar Data Type in Tuple
# Using isinstance() + loop
  
# initializing tuple
test_tuple = (5, 6, 7, 3, 5, 6)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Test Similar Data Type in Tuple
# Using isinstance() + loop
res = True
for ele in test_tuple:
    if not isinstance(ele, type(test_tuple[0])):
        res = False 
        break
  
# printing result 
print("Do all elements have same type ? : " + str(res))

chevron_right


Output :

The original tuple : (5, 6, 7, 3, 5, 6)
Do all elements have same type ? : True

 

Method #2 : Using all() + isinstance()
The combination of above functions can also be used to solve this problem. In this, we test for all the values using all() and isinstance() is used to check for data type.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Test Similar Data Type in Tuple
# Using all() + isinstance()
  
# initializing tuple
test_tuple = (5, 6, 7, 3, 5, 6)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Test Similar Data Type in Tuple
# Using all() + isinstance()
res = all(isinstance(ele, type(test_tuple[0])) for ele in test_tuple)
  
# printing result 
print("Do all elements have same type ? : " + str(res))

chevron_right


Output :

The original tuple : (5, 6, 7, 3, 5, 6)
Do all elements have same type ? : True



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.