Check order specific data type in tuple in Python


When it is required to check the order of a specific data type in a tuple, the 'isinstance' method and the 'chained if' can be used.

The 'isinstance' method checks to see if a given parameter belong to a specific data type or not.

The 'chained if' is a chained conditional statement. It is a different way of writing nested selection statements. It basically means multiple if statements are combined using 'and' operator, and their result is evaluated.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

Below is a demonstration of the same −

Example

Live Demo

my_tuple = ('Hi', ['there', 'Will'], 67)

print("The tuple is : ")
print(my_tuple)

my_result = isinstance(my_tuple, tuple) and isinstance(my_tuple[0], str) and
isinstance(my_tuple[1], list) and isinstance(my_tuple[2], int)

print("Do all instances match the required data type in the same order ? ")
print(my_result)

Output

The tuple is :
('Hi', ['there', 'Will'], 67)
Do all instances match the required data type in the same order ?
True

Explanation

  • A tuple of list is defined, and is displayed on the console.
  • the 'isinstance' method is used to check if the elements ina tuple belong to a certain data type.
  • This is done for all elements within the tuple list, hence the 'and' operator is used to chain the operation.
  • This is assigned to a value.
  • It is displayed on the console.

Updated on: 12-Mar-2021

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements