Python type() Function

The type() function in Python is used when we need to find the type of an object. For example:

x = 10
print(type(x))

x = "Python Programming"
print(type(x))

x = [12, 32, 54, 54]
print(type(x))

x = ('codes', 'cracker', 'dot', 'com')
print(type(x))

The output will be:

<class 'int'>
<class 'str'>
<class 'list'>
<class 'tuple'>

Python type() Function Syntax

The syntax of type() function in Python, is:

type(object, bases, dict)

where object refers to an object whose type we need to find. The bases parameter is used to specify the base classes using tuple. And the third parameter dict refers to a dictionary that is the namespace with the definitions for class.

Note: The first parameter is required, whereas the second and third parameters are optional.

The type() function returns the type of specified object, in case if there is only one (object) parameter is used or passed. Otherwise returns a new type, in case if all the three parameters are passed.

Python type() Function Example

Here is an example of type() function in Python:

x = [1, 2, 4, 5]
if type(x) is list:
    print("The object 'x' is of 'list' type.")
else:
    print("The object 'x' is not a 'list' type.")

x = "fresherearth dot com"
if type(x) is str:
    print("\nThe object 'x' is of 'str' type.")
else:
    print("\nThe object 'x' is not a 'str' type.")

x = 12.434
if type(x) is float:
    print("\nThe object 'x' is of 'float' type.")
else:
    print("\nThe object 'x' is not a 'float' type.")

The output is:

The object 'x' is of 'list' type.

The object 'x' is of 'str' type.

The object 'x' is of 'float' type.

Python type() Function with All Three Parameters

This program is created to demonstrate the type() function in Python, will its all three parameters:

x = type('Python Programming', (object,), dict(Day='Mon', Month='Dec'))
print(type(x))
print(vars(x))

class fresherearth:
    Day = 'Mon'
    Month = 'Dec'

x = type('Python is Fun', (fresherearth,), dict(Day='Mon', Month='Dec'))
print(type(x))
print(vars(x))

The output is:

<class 'type'>
{'Day': 'Mon', 'Month': 'Dec', '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Python Programming' objects>, '__weakref__': <attribute '__weakref__' of 'Python Programming' objects>, '__doc__': None}
<class 'type'>
{'Day': 'Mon', 'Month': 'Dec', '__module__': '__main__', '__doc__': None}

Note: The vars() function returns the __dict__ attribute of specified object.

Python Online Test


« Previous Function Next Function »