How to Returns the type of an object in Python ?


In Python, we can use the type() function to return the type of an object.

Syntax: type(object)

Example:

# Integer
num = 10
print(type(num))  # <class 'int'>

# Float
float_num = 10.5
print(type(float_num))  # <class 'float'>

# String
name = "John"
print(type(name))  # <class 'str'>

# List
my_list = [1, 2, 3]
print(type(my_list))  # <class 'list'>

# Tuple
my_tuple = (1, 2, 3)
print(type(my_tuple))  # <class 'tuple'>

# Dictionary
my_dict = {'name': 'John', 'age': 25}
print(type(my_dict))  # <class 'dict'>

Output:

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

We can also use the isinstance() function to check if an object is an instance of a particular class.

Syntax: isinstance(object, classinfo)

Example:

# Integer
num = 10
print(isinstance(num, int))  # True

# Float
float_num = 10.5
print(isinstance(float_num, float))  # True

# String
name = "John"
print(isinstance(name, str))  # True

# List
my_list = [1, 2, 3]
print(isinstance(my_list, list))  # True

# Tuple
my_tuple = (1, 2, 3)
print(isinstance(my_tuple, tuple))  # True

# Dictionary
my_dict = {'name': 'John', 'age': 25}
print(isinstance(my_dict, dict))  # True

Output:

True
True
True
True
True
True


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.