What is Python type() function?
- In some scenarios, you may require knowing the data type of an object or variables as doing programming in Python.
- Python type() function is one of the available ways of doing this.
- The type() function returns the type of the given object as a type object.
- By specifying the object to the type() function, the single required parameter, it returns the type of the object like a list, integer, float, tuple, etc.
Syntax of type Python function
The syntax of using the type() function for checking the type of object or variable is:
The other use of type() function takes three parameters. That is:
class type(name, bases, dict)
It returns a new type object. (See the last part of this tutorial).
An example of type function
In this example, a list is created with few items. The type() function is used to return its type:
#A demo of type function list_type = [10, 20, 'a', 'b'] print("The type of object is: ", type(list_type))
Output:
A demo of a tuple with type function
For this example, the tuple object is passed to the type function, see what it returns:
tupl_type = (1, 5, 7, 11) print("The type of object is: ", type(tupl_type))
Output:
A dictionary object example
See this example where a dictionary object is created and its type is checked by using the Python type() function.
dir_dict_type = {'Mike': 4785757474,'Riya': 41024547, 'Mina':635363636} print("The type of object is: ", type(dir_dict_type))
Output:
Knowing the type of integer, float, and string variables
As such, the int, float, and string variables are also objects. You may pass these into the type() function to know their data type.
This may be useful for scenarios where you need to read the data, convert it to the appropriate type, and perform some action.
In the following example, the types of a string, int, and float objects are displayed by using the type() function:
#A demo of type function a = 25 b = 40.898 c = "What is your name?" print("a = : ", type(a)) print("b = : ", type(b)) print("c = : ", type(c))
Output:
What is the recommended way of testing the type?
The Python official website recommends using the isinstance() function for testing the type of the objects.
See an example of using the isinstance() function or go to its tutorial.
#A demo of isinstance function lst_type = [15, 30, 45, 'xyz', 'abc'] the_type = isinstance(lst_type, list) print("The type of object is list?", the_type)
Output:
The returned value is true, which means it is a list.
The type function with three parameters
The other syntax used for the type() function takes three parameters. That is:
class type(name, bases, dict)M
For more details on this, visit the official website section here.