Check if variable is tuple in Python

PythonServer Side ProgrammingProgramming

When it is required to check if a variable is a tuple, the 'type' method can be used.  A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.

The 'type' method checks to see the type of the iterable/value that is passed to it as an argument.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)

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

my_result = type(my_tuple_1) is tuple

print("Is the given variable a tuple ? ")
print(my_result)

Output

The tuple is :
(7, 8, 0, 3, 45, 3, 2, 22, 4)
Is the given variable a tuple ?
True

Explanation

  • A tuple is defined, and is displayed on the console.
  • The type of the tuple is examined, and the 'is' and 'tuple' operators are used to check if it is a tuple type.
  • This result is assigned to a value.
  • It is displayed as output on the console.
raja
Published on 11-Mar-2021 10:01:36
Advertisements