How To Check Type Of Variable In Python
Last Updated : Jul 1, 2023
In this article we will show you the solution of how to check type of variable in python, if you're a beginner it's important to have a strong knowledge of data types of variables, and so is to identify the type of a given variable.
Python is a dynamically typed language, that is the interpreter doesn't assign the type of the variable at the compile time, because the type of the variable can be changed in runtime.
There are several data types in Python like str, int, float, complex, list, tuple, range, dict, set, frozenset, bool, bytes, bytearray, and memoryview.
In Python, variables are not declared with data types.
So, knowing the type of variable helps in debugging too if there are any errors in the code.
To get the type of variable in Python, we use the built-in type() function.
Using the type() command, you can pass a single argument, and the return value will be the class type of the argument given.
In Python, everything is an object. Hence, when we use the built-in type() function to determine the type of the value stored in a variable to the console, it returns the class type of the object.
Step By Step Guide On How To Check Type Of Variable In Python :-
- As mentioned above, we are using the type() function to check the type of the variable
- First, I have taken a variable 'name' and the value assigned to it is "TalkersCode"
- Now, in the next line, to check the type of variable, I have used the type() function, along with the print() function, so that the output is displayed.
- As we can see in the code output, the first line displays, the output as <class 'str'>.
- This shows the data type of the variable 'name' is a 'string'.
- We have also taken a second example, in the next line, where a variable named 'languages' is declared and some values are stored in it, actually more than one value is stored in a single variable. So, what will be the data type of this 'languages' variable?
- To find out, again in the next line, we have used the type() function, along with the print() function so that the output is displayed on the screen.
- In the given code output, we can see on the second line that the output is ' <class 'list'> ', showing that the data type of the variable named 'languages' is a 'list'.
Hence, we have learned the concept of the type() function and how to check the type of variable in Python.
Hope this article, helps you to understand the concept of type() function and implement it in Python.
So, give it a go and try out different examples for different data types.
I hope this article on how to check type of variable in python helps you and the steps and method mentioned above are easy to follow and implement.