- How to Check Type of Variable in Python
- 1. Checking Variable Type With Type() built-in function
- what is type()
- syntax
- Example 2: checking if the type of variable is a string
- 2. Checking Variable Type With isinstance() built-in function
- what is isinstance()
- sytnax
- example 1: checking variables type
- 4. Data Types in Python
- Related Tutorials:
- Python Print Type of Variable – How to Get Var Type
- How to Print the Type of a Variable in Python
- Final Thoughts
- Check Object’s Type in Python: 4 Easy Methods (with code)
- What is an Object?
- How to Check the Type of an Object in Python?
- 1) type() function
- 2) isinstance() function
- 03) . class__ attribute
- 4) The ‘==’ operator and type()
- Conclusion
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
As you can see, in the above code we have many different variables,
now let’s get the type of these variables.
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
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
example 1: checking variables type
#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))
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
Related Tutorials:
Python Print Type of Variable – How to Get Var Type
Kolade Chris
If you’re a Python beginner, becoming familiar with all its various data types can be confusing at first. After all, there are a lot of them available to you in the language.
In this article, I’m going to show you how to get the type of various data structures in Python by assigning them to a variable, and then printing the type to the console with the print() function.
How to Print the Type of a Variable in Python
To get the type of a variable in Python, you can use the built-in type() function.
The basic syntax looks like this:
In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
For instance, if the type is a string and you use the type() on it, you’d get as the result.
To show you the type() function in action, I’m going to declare some variables and assign to them the various data types in Python.
name = "freeCodeCamp" score = 99.99 lessons = ["RWD", "JavaScript", "Databases", "Python"] person = < "firstName": "John", "lastName": "Doe", "age": 28 >langs = ("Python", "JavaScript", "Golang") basics =
I will then print the types to the console by wrapping print() around some strings and the type() function.
print("The variable, name is of type:", type(name)) print("The variable, score is of type:", type(score)) print("The variable, lessons is of type:", type(lessons)) print("The variable, person is of type:", type(person)) print("The variable, langs is of type:", type(langs)) print("The variable, basics is of type:", type(basics))
Here are the outputs:
# Outputs: # The variable, name is of type: # The variable, score is of type: # The variable, lessons is of type: # The variable, person is of type: # The variable, langs is of type: # The variable, basics is of type:
Final Thoughts
The type() function is a valuable built-in function of Python with which you can get the data type of a variable.
If you’re a beginner, you should save yourself the hassle of cramming data types by using the type() function to print the type of a variable to the console. This will save you some time.
You can also use the type() function for debugging because in Python, variables are not declared with data types. So, the type() function was built into the language for you to check for data types of variables.
Check Object’s Type in Python: 4 Easy Methods (with code)
Knowing how to check an object’s type in python before executing any operations on it is a fundamental task that you’ll come across regularly whether you’re working on a production system, or a personal project. If you’re just getting started or have experience with the language, this will help to produce better code.
What is an Object?
To understand the concept well, one should remember that Python is primarily an object-oriented programming language. That means that everything in python is an object with properties and methods.
An object is an instance of a class. A class is a boilerplate or a blueprint of an object that contains all the methods and data variables necessary. For example, in Python, ‘int’ is a class. When we assign a number to a variable, the datatype ‘int’ is dynamically assigned to the variable.
How to Check the Type of an Object in Python?
There are many methods in python to determine the type of an object. The built-in type() function will be covered at first, followed by more complex techniques like the isinstance() function, the __class__ attribute, and others.
1) type() function
To determine the type of an object, this method the simplest way. The type() function is a built-in method in python that returns the type of an object as an argument. It will be useful to check the type for performing operations on it.
For instance, we can use the following code to determine the type of the integer 5:
As we can see, the output of the type() function is a class that represents the type of the object. In this case, the type of integer 5 is int.
The function returns the class name and it gives the complete necessary information about the object’s type. But, Python being the versatile language that it is, there are many other ways to find or check the Object type without explicitly using the ‘type()’ function.
2) isinstance() function
The isinstance() function takes an object and a class as arguments and returns True if the object is an instance of the class, and False otherwise. It compares both arguments and returned the boolean value of the comparison.
For example, to check if the integer 5 is an instance of the int class, we can use the following code:
x = 5 print(isinstance(x, int))
The isinstance() function returns a boolean value of True or False by comparing the class of the variable to the class passed as the argument in the function. In the above example, we’ve passed ‘x’ which has the integer 5 assigned to it as one argument and we’ve passed ‘int’ as the second argument.
However, it is only beneficial if one wants to check if the Object type is what they think it is because it does not return the type name. So, isinstance() function is more for the sake of verification than finding out.
03) . class__ attribute
As mentioned earlier in the article, everything in Python is an object and every object has its attributes the one attribute that would return the class type of the Object is aptly called the ‘__class__’ attribute. In addition to built-in functions, there is another way to check object type in Python is by using the __class__ attribute.
Python objects each have a __class__ attribute that includes the object’s class information. For instance, the following code can be used to determine the class of integer 5.
The type() function essentially returns the __class__ attribute from the object. The above example is more of an explicit way of accessing the attribute without the need for any methods.
If we were to implement the functionality of isinstance() function without actually calling it, we can use the ‘==’ comparison operator to compare between the type we guess and the type of the object. Comparison operators return a boolean value of either True or False. ‘==’ returns True if two things being compared are equal and False if not equal.
4) The ‘==’ operator and type()
Using the type() function and the == operator is another technique to determine an object’s type. This can be used to contrast an object’s type with a particular class. For instance, we can use the following code to determine whether the integer 5 is of type int:
It’s important to remember that Python is a dynamically typed language, which means that a variable’s type may change while it is being used. Because of this, it may be required to confirm the type of an item before carrying out specific operations. To add two numbers, for instance, we must ensure that they are both integers or floats.
x = 15 print(type(x)) x = "text" print(type(x))
The above code demonstrates how the object type of a variable can change during runtime. The output for this example will be the following:
The first print statement displayed the type to be ‘int’ as 15 is an integer but after a string was assigned to the same variable, the same print statement displayed the type to be ‘str’ because of the dynamic change of object type.
The dynamically typed nature of python makes the action of checking object types highly essential. For example, if we want to add two numbers, we need to make sure that both are integers or float. Operations on incompatible class types would result in errors that can only be debugged through functions like type() or through the other approach of accessing the ‘__class__’ attribute.
Conclusion
In conclusion, knowing how to check an object’s type in Python is essential for any beginner to comprehend the various techniques, their benefits and drawbacks, and when to apply them in various circumstances. While the type() function is preferred, you have other options in your stock.