Check Variable Type in Python

Python doesn’t offer exactly the same types of variables as for example C++.
For this reason, you can’t check whether the particular integer is 16-bit, 32-bit or unsigned.

That’s all done behind the scene. But you can determine, for example, whether the variable is an integer or a string.

If you want to check a type of a variable or object you have to use the type function.

a = 123
print(type(a))
b = 123.6
print(type(b))

This will return the following result.

<class 'int'>
<class 'float'>

Python returns the names of data types in the form that is not particularly elegant. Let’s create a function that will format the result to a more readable form.

def return_type(variable):
    var_type = type(variable).__name__

    return var_type

Now, let’s assign some values to variables and objects and print them on a console. We will do it for int, float, str, list, dict, tuple, complex, set, bool.

a = 123
b = 123.6
c = '123'
d = ['123', 456]
e = {'name': 'John', 'lastname': 'Williams'}
f = ('123', 456)
g = 3.14J
h = {1, 2, 3}
i = True

print(return_type(a))
print(return_type(b))
print(return_type(c))
print(return_type(d))
print(return_type(e))
print(return_type(f))
print(return_type(g))
print(return_type(h))
print(return_type(i))

This will give us the following result.

int
float
str
list
dict
tuple
complex
set
bool