Open In App

Python | Check order specific data type in tuple

Improve
Improve
Like Article
Like
Save
Share
Report

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 this, we sometimes, need to check for record’s data types according to their ordering. Let’s discuss certain ways in which this task can be performed.

Method #1: Using chained if and isinstance()

This task can be performed using a combination of the above functionalities. In this, we just need to test for the data type using the isinstance(), and to check each element of the tuple we employ chained if statements.

Python3




# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using chained if and isinstance()
 
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Check order specific data type in tuple
# Using chained if and isinstance()
res = isinstance(test_tup, tuple)\
    and isinstance(test_tup[0], str)\
    and isinstance(test_tup[1], list)\
    and isinstance(test_tup[2], int)
 
# printing result
print("Does all the instances match required data types in order ? : " + str(res))


Output : 

The original tuple is : ('gfg', ['is', 'best'], 1)
Does all the instances match required data types in order ? : True

 

 
Method #2: Using map() + type() + instance():

The combination of above functions can also be used to achieve this task. The checking for types for each element in tuple is extended by map(). The advantage of this method is that it allows us to define the data type ordering beforehand as a list. 

Python3




# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using map() + type() + isinstance()
 
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# data type order list
data_list = [str, list, int]
 
# Check order specific data type in tuple
# Using map() + type() + isinstance()
res = isinstance(test_tup, tuple) and list(map(type, test_tup)) == data_list
 
# printing result
print("Does all the instances match required data types in order ? : " + str(res))


Output : 

The original tuple is : ('gfg', ['is', 'best'], 1)
Does all the instances match required data types in order ? : True

 

Method #3: Using zip() and all()

This method uses the zip() function to create a list of tuples where each tuple contains the element of the test tuple and the corresponding data type in the data type list. Then, the all() function is used to check if all elements in the list of tuples returned by the zip() function satisfy the isinstance() condition.

Python3




# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using zip() and all()
 
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
 
# data type order list
data_list = [str, list, int]
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Check order specific data type in tuple
# Using zip() and all()
res = all(isinstance(x, y) for x, y in zip(test_tup, data_list))
 
# printing result
print("Does all the instances match required data types in order ? : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original tuple is : ('gfg', ['is', 'best'], 1)
Does all the instances match required data types in order ? : True

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 4: Using a loop to iterate through the tuple and compare data types

Approach:

  1. Initialize a tuple with elements of different data types
  2. Create a list of data types in the order they are expected in the tuple
  3. Print the original tuple
  4. Initialize a boolean variable match to True. This variable will keep track of whether all the elements in the tuple match the expected data types in the correct order.
  5. Use a for loop to iterate through each element in the tuple. Check if the data type of the current element in the tuple matches the corresponding data type in the data_list. If it does not match, set match to False and break out of the loop.
  6. Print the result indicating whether all the instances in the tuple match the required data types in order.

Implementation:

Python3




# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using a loop to iterate through the tuple and compare data types
 
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
 
# data type order list
data_list = [str, list, int]
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Check order specific data type in tuple
# Using a loop to iterate through the tuple and compare data types
match = True
for i in range(len(test_tup)):
    if not isinstance(test_tup[i], data_list[i]):
        match = False
        break
 
# printing result
print("Does all the instances match required data types in order ? : " + str(match))


Output

The original tuple is : ('gfg', ['is', 'best'], 1)
Does all the instances match required data types in order ? : True

Time complexity: O(n), where n is the length of the tuple. 
Auxiliary space: O(1), since we only use a constant amount of additional memory (the match variable).

Method 5: Using the reduce() function from the functools module

This method uses the reduce() function from the functools module to iterate through the tuple and the data type order list simultaneously, comparing the data types of the elements. The reduce() function applies a function (in this case, a lambda function) to the elements of the tuple and the data type order list in a cumulative way, comparing each element in turn. The initial value of the accumulator variable is set to True, indicating that all the instances match the required data types in order. If a mismatch is found, the accumulator variable is set to False, indicating that not all the instances match the required data types in order.

Approach:

  1. Import the reduce() function from the functools module.
  2. Initialize the tuple test_tup and the data type order list data_list.
  3. Use the reduce() function to apply a lambda function to the elements of the tuple and the data type
  4. order list in a cumulative way, comparing each element in turn. The lambda function should take two arguments: the accumulator variable and the current element. The isinstance() function is used to compare the data types of the elements. The initial value of the accumulator variable is set to True, indicating that all the instances match the required data types in order.
  5. Print the result 

Python3




# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using the reduce() function from the functools module
 
from functools import reduce
 
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
 
# data type order list
data_list = [str, list, int]
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Check order specific data type in tuple
# Using the reduce() function from the functools module
match = reduce(lambda acc, x: acc and isinstance(
    x[0], x[1]), zip(test_tup, data_list), True)
 
# printing result
print("Does all the instances match required data types in order ? : " + str(match))


Output

The original tuple is : ('gfg', ['is', 'best'], 1)
Does all the instances match required data types in order ? : True

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

Method  6: Using recursion

Approach: 

  1. Define the tuple test_tup with three elements: a string, a list of strings, and an integer.
  2. Define the list data_list with three elements: str, list, and int. This is the data type order list.
  3. Print the original tuple test_tup.
  4. Define a function match_data_type that takes in two arguments: data_list and test_tup. This function uses recursion to check if each element’s data type in the tuple matches the corresponding data type in the data_list.
  5. If either data_list or test_tup is empty, the function returns True.
  6. If the first element of test_tup matches the corresponding data type in the data_list, the function calls itself recursively with the remaining elements.
  7. If the first element of test_tup does not match the corresponding data type in the data_list, the function returns False.
  8. Call the function match_data_type with data_list and test_tup as arguments, and assign the result to the variable match.
  9. Print the result of whether all the instances match the required data types in order.

Python3




# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using recursion
 
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
 
# data type order list
data_list = [str, list, int]
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Check order specific data type in tuple
# Using recursion
 
 
def match_data_type(data_list, test_tup):
    if not data_list or not test_tup:
        return True
    elif isinstance(test_tup[0], data_list[0]):
        return match_data_type(data_list[1:], test_tup[1:])
    else:
        return False
 
 
match = match_data_type(data_list, test_tup)
 
# printing result
print("Does all the instances match required data types in order? : " + str(match))


Output

The original tuple is : ('gfg', ['is', 'best'], 1)
Does all the instances match required data types in order? : True

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



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