Home »
Python
How to determine a Python variable's type?
By IncludeHelp Last updated : December 07, 2024
Determining Python Variable's Type
To determine the type of a variable, you can simply use either type() or isinstance() methods, both methods are built-in methods of the Python standard library. In this tutorial, we will be learning about these methods, and how can we use these methods to determine the type of a specific variable/object.
1. By using the type() method
If a single argument is passed to type(), it returns type of the given object.
Syntax
type(object)
Example to determine variable's type using type() method
Determine the type of a string and an integer variable using the type() method.
# Creating two variables
test_string = "yes"
test_number = 1
# Printing their types
print("Type of test_string is:", type(test_string))
print("Type of test_number is:", type(test_number))
Output:
Type of test_string is: <class 'str'>
Type of test_number is: <class 'int'>
2. By using the isinstance() method
The isinstance() function checks if the object (first argument ) is an instance or subclass of classinfo class (second argument)
Syntax
isinstance(object, classinfo)
Here, object: object to be validated, and classinfo: class, type, or tuple of classes and types
Return value: true if the object is an instance or subclass of a class, or any element of the tuple, false otherwise. If the classinfo is not a type or a tuple of types, a TypeError exception is raised.
Example to determine variable's type using isinstance() method
This example demonstrates the use of isinstance() method.
class Example:
name = "include_help"
ExampleInstance = Example()
print(isinstance(ExampleInstance, Example))
print(isinstance(ExampleInstance, (list, set)))
print(isinstance(ExampleInstance, (list, set, Example)))
Output:
True
False
True
Comparison between type() and isinstance() methods
type() |
isinstance() |
It returns the type object of an object and comparing what it returns to another type object will only return True when the same type object are on both sides. |
In order to see if an object has a certain type, use isinstance() as it checks to see if the object passed in the first argument is of the type of any of the type objects passed in the second argument. Hence, it works as expected with subclassing and old-style classes, all of which have the legacy type object instance. |