Python - Test Similar Data Type in Tuple
Last Updated :
27 Apr, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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
- 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.
- Step-by-step approach:
- Initialize a variable data_type with the type of the first element of the tuple using type() function.
- 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.
- If the loop completes without catching a TypeError exception, then all elements are of the same type, and set the res variable to True.
- 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))
OutputThe 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).
Similar Reads
Python | Check order specific data type in tuple Sometimes, while working with records, we can have a problem in which we need to test for the correct ordering of data types inserted while filling forms, etc. at the backend. These tests are generally handled at frontend while web development but are recommended to be tested at backend as well. For
8 min read
Python | Get tuple element data types Tuples can be a collection of various data types, and unlike simpler data types, conventional methods of getting the type of each element of tuple is not possible. For this we need to have different ways to achieve this task. Let's discuss certain ways in which this task can be performed. Method #1
5 min read
Tuple within a Tuple in Python In the realm of Python programming, tuples offer a flexible solution for organizing data effectively. By allowing the inclusion of other tuples within them, tuples further enhance their capabilities. In this article, we will see how we can use tuple within a tuple in Python. Using Tuple within a Tup
4 min read
Python - Test if Tuple contains K Sometimes, while working with Python, we can have a problem in which we have a record and we need to check if it contains K. This kind of problem is common in data preprocessing steps. Letâs discuss certain ways in which this task can be performed. Method #1: Using any() + map() + lambda Combination
6 min read
Python | Test if tuple is distinct Sometimes, while working with records, we have a problem in which we need to find if all elements of tuple are different. This can have applications in many domains including web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is a brute force
4 min read
Python - Test if tuple list has Single element Given a Tuple list, check if it is composed of only one element, used multiple times. Input : test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Output : True Explanation : All elements are equal to 3. Input : test_list = [(3, 3, 3), (3, 3), (3, 4, 3), (3, 3)] Output : False Explanation : All elemen
7 min read