Last modified: Jan 10, 2023 By Alexander Williams
How to Check Type of Variable in Python
In this tutorial, we'll learn about getting and testing the type of variables by using two different ways, and finally, we'll know the difference between these two ways.
1. Checking Variable Type With Type() built-in function
what is type()
type() is a python built function that returns the type of objects
syntax
type(object)
Example 1: Getting the type of variable
""" in this code, we have many different types of variables """
#list
variable_1 = [1, 2, 3]
#string
variable_2 = "hello programmers"
#tuple
variable_3 = (1, 2, 3)
#dictionry
variable_4 = {"hello":"programmers"}
As you can see, in the above code we have many different variables,
now let's get the type of these variables.
""" in this code, we'll get the type of our variables """
print(type(variable_1))
print(type(variable_2))
print(type(variable_3))
print(type(variable_4))
output
<class 'list'>
<class 'str'>
<class 'tuple'>
<class 'dict'>
If you want to know all types of objects in python, you'll find it in the final part of the article.
Example 2: checking if the type of variable is a string
let's say that you want to test or check if a variable is a string, see the code bellow
""" in this code, we'll check if a variable is a string """
#variable
variable_2 = "hello programmers"
#check the typle of variable_2
if type(variable_2) is str:
print("Yes it is")
output
Yes it is
As you can see, the code works very well, but this is not the best way to do that.
Remember!, if you want to check the type of variable, you should use isinstance() built function.
2. Checking Variable Type With isinstance() built-in function
what is isinstance()
The isinstance() is a built-in function that check the type of object and return True or False
sytnax
isinstance(object, type)
example 1: checking variables type
""" in this code, we'll check or test the variable's type """
#list
list_var = [1, 2, 3]
#string
string_var = "hello programmers"
#tuple
tuple_var = (1, 2, 3)
#dictionry
dictionry_var = {"hello":"programmers"}
#check if "list_var" is list
print(isinstance(list_var, list))
#check if "string_var" is tuple
print(isinstance(string_var, tuple))
#check if "tuple_var" is tuple
print(isinstance(tuple_var, tuple))
#check if "dictionry_var" is dictionary
print(isinstance(dictionry_var, dict))
output
True
False
True
True
example 2: Doing something after checking variable type
""" in this code, we'll print 'Yes' if the variable is a string """
#string
string_var = "hello programmers"
if isinstance(string_var, str) == True:
print("Yes")
output
Yes
3. When you should use isinstance() and type()
if you want to get type of object use type() function.
if you want to check type of object use isinstance() function
4. Data Types in Python
str
int
float
complex
list
tuple
range
dict
bool
bytes