Python | Check if variable is tuple

Sometimes, while working with Python, we can have a problem in which we need to check if a variable is single or a record. This has applications in domains in which we need to restrict the type of data we work on. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using type()
This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check if variable is tuple
# using type()
  
# initialize tuple 
test_tup = (4, 5, 6)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Check if variable is tuple
# using type()
res = type(test_tup) is tuple
  
# printing result
print("Is variable tuple ? : " + str(res))

chevron_right


Output :

The original tuple : (4, 5, 6)
Is variable tuple ? : True

 

Method #2 : Using isinstance()
Yet another function that can be employed to perform this task. It also returns true, in case the parent class of variable(if exists) is a tuple.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check if variable is tuple
# using isinstance()
  
# initialize tuple 
test_tup = (4, 5, 6)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Check if variable is tuple
# using isinstance()
res = isinstance(test_tup, tuple
  
# printing result
print("Is variable tuple ? : " + str(res))

chevron_right


Output :

The original tuple : (4, 5, 6)
Is variable tuple ? : True

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.