Python type() Function Tutorial

Python provides the type() function in order to return class or object type. The object or variable is provided as a parameter to the type() function. The type() function is mainly used to debug applications and scripts to check different types or compare different objects or variable types with each other.

type() Function Syntax

The type() function has two different syntaxes. The first syntax is very simple where a single parameter is provided which is an object or variable.

  • OBJECT is an object or variable whose type is returned.
  • NAME is the name of the class, which later corresponds to the __name__ attribute of the class.
  • BASES is a tuple of classes from which the current class derives.
  • DICT is a dictionary that holds the namespaces for the class.

Check Variable/Object Type

One of the most popular use cases for the type() function is checking variable or object type. In the following example, we check different object types like list, tuple, dictionary, integer, etc.


<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'int'>

Compare Variable/Object Type

Another popular usage for the type() function is comparing variables or objects with each other. The if statement is used for the comparison with the is operator.

a = [1,2,3]

b = [4,5,6]

c = (1,2,3)

d = {"a":"a","b":"b"}

e = 5

if type(a) is type(b):
   print("a and b same types")

if type(a) is type(c):
   print("a and c same types")

if type(c) is type(c):
   print("c and c same types")

if type(e) is type(10):
   print("e and 10 same types")
a and b same types
c and c same types
e and 10 same types

Leave a Comment