How to check the datatype of objects in Python

In this Answer, we will learn how to check if an object is of a certain data type in Python.

What are objects in Python?

Just as in every programming language, an object is an instance of a class, while a class is simply a template for creating objects with similar methods and properties.

In simpler terms, If we are creating an object, we are simply creating an instance of a class. The object you created has its own set of attributes and methods that are used to communicate with it. For example, when we create an object (e.g. "hello" ), which is an instance of the class str, we can interact with this object by using some methods, such as upper(), lower(), strip(), join(), and many more.

Below is a table showing some of the most common classes in Python and examples of its instance or objects:

Classes and Their Examples (Object)

Class

Description

Example (objects)

int

Integer values

1, 2, 3

float

Floating-point values

1.0, 2.5, 3.14159

str

String of characters

"hello", "world"

list

Ordered sequence of objects that are mutable

[1, 2, 3], ["a", "b", "c"]

tuple

Ordered sequence of objects that are not mutable

(1, 2, 3), ("a", "b", "c")

dict

A dictionary: mapping of keys to values

{"a":1, "b"::2, "c":3}

set

A set: unordered collections of unique objects

{"a", "b", "c"}, {1, 2, 3}

bool

Boolean values

True, False

NoneType

Null values

None

Note: The table above shows only the built in classes in Python. We can also create our own class using the class keyword.

How to check for the data type of an object

To check if an object is of a certain data type in Python, we use the type() function.

Syntax

type(x)

Where x represents the object of which the data type is to be obtained.

Code example

In the code below, we will create some objects and check for the data type using the type() function:

# Basic data types
my_int = 42
my_float = 3.14159
my_string = "Hello, World!"
# Data structures
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
my_dict = {"a": 1, "b": 2, "c": 3}
# A function
def my_function():
pass
# A class
class MyClass:
pass
all_objects = [my_int,
my_float,
my_string,
my_list,
my_tuple,
my_dict,
my_function,
MyClass ]
for objects in all_objects:
print(objects, f"-------is of data type {type(objects)}\n")

Code explanation

  • Lines 1–17: We create some object of different classes in Python.

  • Lines 19–26: We create a list all_objects to house all the objects we created.

  • Lines 28–29: We iterate over the list of all the objects we created and obtain their data types using the type() function.

Free Resources