EN
Python - check object / variable type
0
points
In this article, we would like to show you how to check object / variable type in Python.
Quick solution:
my_int = 123
print(type(my_int)) # <class 'int'>
print(isinstance(my_int, int)) # True
1. Practical example using type()
In this example, we use built-in type()
function to check the type of given variables.
my_string = 'abc'
my_int = 123
my_float = 1.23
my_bool = True
my_list = [4, 5, 6]
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_tuple = ('A', 'B', 'C', 'D')
my_set = {'A', 'B', 'C', 'D'}
print(type( my_string )) # <class 'str'>
print(type( my_int )) # <class 'int'>
print(type( my_float )) # <class 'float'>
print(type( my_bool )) # <class 'bool'>
print(type( my_list )) # <class 'list'>
print(type( my_dict )) # <class 'dict'>
print(type( my_tuple )) # <class 'tuple'>
print(type( my_set )) # <class 'set'>
Output:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
<class 'set'>
2. Practical example using isinstance()
In this example, we use built-in isinstance()
function to check the type of given variables.
my_string = 'abc'
my_int = 123
my_float = 1.23
my_bool = True
my_list = [4, 5, 6]
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_tuple = ('A', 'B', 'C', 'D')
my_set = {'A', 'B', 'C', 'D'}
print(isinstance( my_string, str )) # True
print(isinstance( my_int, int )) # True
print(isinstance( my_float, float )) # True
print(isinstance( my_bool, bool )) # True
print(isinstance( my_list, list )) # True
print(isinstance( my_dict, dict )) # True
print(isinstance( my_tuple, tuple )) # True
print(isinstance( my_set, set )) # True
Output:
True
True
True
True
True
True
True
True