In this article, we will learn how to find the type of a variable in Python no matter what is stored in that variable. The variable can have a list, some class object, string, number, tuple or anything else.
We use the type()
function to find the type of any variable in python.
Python type()
Function
This function has a very simple syntax and can be used to find the type of any variable in python be it a collection type variable, a class object variable or a simple string or integer. Below is the syntax,
type(<VARIABLE_NAME>)
Let's take an example for different datatypes and see the output.
a = 12
print(type(a))
Output:
<class 'int'>
Let's take another example,
a = 1000000000
print(type(a))
Output:
<class 'int'>
In python 2.x version, the output for the above code will be <class 'long'>
, but from python 3.x onwards, there is only one datatype which is int
, which is equivalent to long
of python 2.x version.
For a literal sequence of characters or a string variable,
a = 'Hello World!'
print(type(a))
Output:
<class 'str'>
If you want to get the name of the datatype only then you can use the __name__
attribute along with the type()
function. Below we have an example for that too.
a = '3.14159'
print(type(a).__name__)
Output:
'float'
The code examples till now were about basic datatypes, now let's see a few code examples for list, tuples, etc.
my_list = [1, 2, 3, 4]
my_tuple = (1, 2, 3, 4)
print(type(my_list))
print(type(my_tuple))
Output:
<class 'list'>
<class 'tuple'>
Using type()
function for User-defined Class Objects
Now let's try and use the type()
function for identifying the type for any object of a custom class and see if it returns the correct value.
class Studytonight:
# init method
def __init__(self):
print("Object initialised")
st = Studytonight()
print(type(st))
Output:
Object initialised
<class '__main__.Studytonight'>
So, we can use the type()
function to find the type of all kind of variables objects. If you face any problem while executing any of the above code examples, or if have any doubt, post them in comments. We would be more than happy to help.
You may also like: