Python has many built-in functions. In this tutorial, we will be discussing how to check the data type of the variables in python by using type(). As while programming in Python, we came to a situation where we wanted to check the data-type of the variable we use type() function. This article will help you understand the concept of type() function.
What is type() function?
Python type() is a built-in function that helps you find the class type of the variable given as input. You have to just place the variable name inside the type() function, and python returns the datatype.
Mostly, We use it for debugging purposes. we can also pass three arguments to type(), i.e., type(name, bases, dict). In such a case, it will return you a new type of object.
Syntax
type(object)
Parameter
The object argument is the required parameter to be passed inside the type() function. The argument can be string, integer, list, tuple, set, dictionary, float, etc.
Syntax
type(name, bases, dict)
Parameter
- name: It is the name of the class.
- bases: It is the optional parameter, and it is the name of the base class.
- dict: It is an optional parameter, and it is the namespace that has a definition of the class.
Return value
- If we pass only the object as the parameter, it will only return the object’s type.
- If we pass the name, bases, and dict as the parameter, it will return the new type.
Examples to Check Data Type in Python
Let us discuss certain ways through which we can print the datatype of the variable.
1. Using type(object) Method to Check Data Type in Python
In this example, we will be taking the input in all the forms to write the variable like string, integer, negative value, float value, complex number, list, tuple, set, and dictionary. After that, we will print the data type of all the variables and see the output.
#taking input
str = 'Python pool'
print('Datatype : ',type(str))
num = 100
print('Datatype : ',type(num))
neg = -20
print('Datatype : ',type(neg))
float = 3.14
print('Datatype : ',type(float))
complex = 2 + 3j
print('Datatype : ',type(complex))
lst = [1,2,3,4,5]
print('Datatype : ',type(lst))
Tuple = (1,2,3,4,5)
print('Datatype : ',type(Tuple))
Dict = {"a" : 2, "b" :3, "c" :1}
print('Datatype : ',type(Dict))
set = {'a', 'b', 'c', 'd'}
print('Datatype : ',type(set))
Output:
Datatype : <class 'str'>
Datatype : <class 'int'>
Datatype : <class 'int'>
Datatype : <class 'float'>
Datatype : <class 'complex'>
Datatype : <class 'list'>
Datatype : <class 'tuple'>
Datatype : <class 'dict'>
Datatype : <class 'set'>
Explanation:
First, we declare the variables and then check the type using the type() function.
2. Using type(name, bases, dict) method to Check Data Type in Python
In this example, we will be taking all the parameters like name, bases, and dict. after that, we will print the output. Let see more clearly with the help of the program.
class Python:
x = 'python pool''
y = 100
t1 = type('NewClass', (Python,), dict(x='Python pool', y=100))
print(type(t1))
print(vars(t1))
Output:
<class 'type'>
{'x': 'Python pool', 'y': 100, '__module__': '__main__', '__doc__': None}
Explanation:
- Firstly, we have taken a class, Python.
- Then, we have taken a string and integer value inside the class python.
- Then, we have taken a variable as t1 in which we have applied the type() with the parameter as name, bases, and dict
- After that, we have printed the type of t1 and vars of t1.
- At last, you can see the output.
Difference between type() and isinstance()
Type() Function
Python type() is a built-in function that helps you find the class type of the variable given as input.
Isinstance() Function
Python isinstance() function is used to check if the object (first argument) is an instance or subclass of classinfo class (second argument).
Example of type() and isinstance() function
In this example, we will be discussing about both the functions and explained in detail.
age = 100
print("Datatype : ",type(age))
age = isinstance(100,int)
print("age is an integer:", age)
Output:
Datatype : <class 'int'>
age is an integer: True
Explanation:
- Firstly, we have taken age as a variable with a value equal to 100.
- Then, we have printed the datatype of the age value.
- After that, we have applied
isinstance()
function with two parameters as the value of age and type of age. - At last, we have printed the output.
- By seeing the output, we can see the difference between the type and
isinstance
function.
Checking Array Data Type (using if hasattr(N, “_len_”))
You can check the array data type using hasattr() function in python by specifying the function. For this you need to know the functions of the array. Here, __len__ provides the length of the data which you have passed. So if hasattr can determine a function that belongs to the array, we can call it array data type. Here, the function which we’ll use is __len__.
For example,
arr=[1,2,3]
if hasattr(arr, '__len__'):
print('array found')
else:
print('not found')
#array found (Output)
Here, the __len__ function determined the length of the arr that was passed as an argument. This function belongs to array data type so we used ‘if’ to see if this attribute is present in array.
Checking for datatype of variable, else raise error (Using assert)
The syntax of assert is :
assert condition, message
It is used just like ‘raise’ to throw an exception but here, a condition is also specified.
Example:
x = 'abc'
print(type(x))
assert type(x) != int, 'x is an integer'
print('x is not an integer')
Check if data type is boolean python
We can assess whether the given data belongs to boolean or not. In this case, you will put either True or False as the input to get a boolean type.
a = True
type(a)
#class<bool>
The type function is an easy-to-use tool to find the data type in Python.
Check data type Python Dataframe
To find the data type for a dataframe in python, you may use the dtype function.
For example,
import pandas as pd
df = pd.DataFrame({'A':[10,11], 'C':[1.3, 0.23]})
print("DataFrame:")
print(df)
result = df.dtypes
print("Output:")
print(result)
#Make sure that all the columns have the same size
And you will obtain the given output
DataFrame:
A C
0 10 1.30
1 11 0.23
Output:
A int64
C float64
dtype: object
FAQs
It is a function that helps to find out the data type of the attributes of a dataframe object in python.
We can check it using the type function.
var = 4 if type(var)==int: print(“Numeric”) else: print(“Not numeric”)
Conclusion
In this tutorial, we have learned how to check the variable’s data type by using type() with two different parameters. We have also explained all the variables using type() with examples explained in detail.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.