Get data type in Python

Contrary to other programming languages, such as C++ or Java, you don’t specify the data type when defining a variable in Python, but it doesn’t mean that the variable doesn’t have a type.

You can check the variable type using the type function that returns the type of data.

Here’s how it works:

a = 1
b = float(a)
c = 1.45
d = 'text'
e = ''
f = None

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))

This code returns this result:

 <class 'int'>
 <class 'float'>
 <class 'float'>
 <class 'str'>
 <class 'str'>
 <class 'NoneType'> 

You can also check types of data structures. Here’s is an example of a list, dictionary, and tuple.

my_list = ['cat', 4, 'emu', 'dog', '.']
my_dict = {'animal': 'chicken'}
my_tuple = (5, 'test', 2)

print(type(my_list))
print(type(my_dict))
print(type(my_tuple))

The result:

<class 'list'>
<class 'dict'>
<class 'tuple'>