Open In App

Python – Test Similar Data Type in Tuple

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python tuples, we can have a problem in which we need to test if all the elements in the tuple have the same data type. This kind of problem can have applications 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. 

Python3




# 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))


Output : 

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

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

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. 

Python3




# 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))


Output : 

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

Method #3: Using type() + loop

Python3




# Python3 code to demonstrate working of
# Test Similar Data Type in Tuple
# Using type() + 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 type() + loop
res = True
x=list(test_tuple)
for ele in x[1:]:
    if not type(ele) is type(x[0]):
        res=False
        break
# printing result
print("Do all elements have same type ? : " + str(res))


Output

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

Method #4: Using filter(),lambda functions

Python3




# Python3 code to demonstrate working of
# Test Similar Data Type in Tuple
 
# 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 type() + loop
res = False
first_type = type(test_tuple[0])
 
result = list(filter(lambda x: type(x) == first_type, test_tuple))
if(len(result) == len(test_tuple)):
    res = True
# printing result
print("Do all elements have same type ? : " + str(res))


Output

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

Time complexity: O(n), where n is the number of elements in the tuple. 

Auxiliary space: O(1), as the code uses only a few constant variables, and the filter() function returns an iterator that doesn’t require extra space.

Method #5: Using set() and isinstance()

Step-by-step approach:

  • Initialize the tuple test_tuple.
  • Use set() to get the unique data types present in the tuple.
  • If the length of the set is greater than 1, it means that there are multiple data types in the tuple. If the length of the set is 1, use isinstance() to check if all elements in the tuple have the same data type.
  • If all elements have the same data type, set res to True, else False.
  • Print the result.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Test Similar Data Type in Tuple
 
# 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 set() and isinstance()
res = False
types = set(map(type, test_tuple))
if len(types) == 1:
    data_type = types.pop() if types else None
    res = all(isinstance(x, data_type) for x in test_tuple)
 
# printing result
print("Do all elements have same type ? : " + str(res))


Output

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

Time complexity: O(n), where n is the length of the tuple.
Auxiliary space: O(1).

Method 6: Using exception handling

  1. This method involves using a try-except block to catch any TypeError exceptions that occur when checking if all elements are of the same type. If no exception is caught, then all elements are of the same type.
  2. Step-by-step approach:
  3. Initialize a variable data_type with the type of the first element of the tuple using type() function.
  4. Use a try-except block to iterate over the remaining elements of the tuple using a for loop, checking if each element is of the same type as the first element. If an element is found to be of a different type, catch the TypeError exception and set the res variable to False.
  5. If the loop completes without catching a TypeError exception, then all elements are of the same type, and set the res variable to True.
  6. Print the result.

Python3




# Python3 code to demonstrate working of
# Test Similar Data Type in Tuple
 
# 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 exception handling
res = True
data_type = type(test_tuple[0])
 
try:
    for x in test_tuple[1:]:
        if not isinstance(x, data_type):
            raise TypeError
except TypeError:
    res = False
 
# printing result
print("Do all elements have same type ? : " + str(res))


Output

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

Time complexity: O(n) where n is the length of the tuple.

Auxiliary space: O(1).



Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads