Python type()

Python type()

Python type() builtin function returns a type object representing the type of argument passed to it.

In Python, the datatype of variable is not declared, but inferred from the value stored in it. So, if you would like to know the type of data that is stored in a variable, you can use type() function.

Syntax of type()

The syntax of type() function is

type(object)

type() returns the type of object.

Example 1: Python type()

In this example, we will assign an integer to a variable, and pass this object to type() function. type() function should return that the object is of type int.

Python Program

x = 69
print(type(x))
Run this program

Output

<class 'int'>

Example 2: Python type() for Builtin types

In this example, we will try to find the type of values stored in variables for all builtin datatypes.

In the following program, we will take a variable named x, assign it a value, find its type, reassign another value, find its, and continue the process for all builtin datatypes.

Python Program

x = 'Hello World'
print(type(x))
x = 69
print(type(x))
x = 3.14159
print(type(x))
x = 3 + 2j
print(type(x))
x = ['apple', 'banana', 'mango']
print(type(x))
x = ('apple', 'banana', 'mango')
print(type(x))
x = range(6)
print(type(x))
x = {'a' : 65, 'b' : 66}
print(type(x))
x = {'apple', 'banana', 'mango'}
print(type(x))
x = frozenset({'apple', 'banana', 'mango'})
print(type(x))
x = True
print(type(x))
x = b'mango juice'
print(type(x))
x = bytearray(5)
print(type(x))
x = memoryview(bytes(5))
print(type(x))
Run this program

Output

<class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'range'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>

Example 3: Python type() for User Defined Datatype

In this example, we will create a new type using class, and find the class objects type using type() function.

Python Program

class Fruit:
    def __init__(self, name):
        self.name = name

x = Fruit('banana')
print(type(x))
Run this program

Output

<class '__main__.Fruit'>

Example 4: Python type of type object

This is deep. We will try to find the type of object returned by type() function using type() function.

Python Program

x = 12
print(type(type(x)))
Run this program

Output

<class 'type'>

The type of type object is type.

Summary

In this tutorial of Python Examples, we learned how to use type() function to find the type of object passed to it.