Summary: In this tutorial, you will learn to compare data types of different objects and variable in Python.

Comparing types determines whether the types of two or more objects are the same.

For example, [1, 2, 3] and ["a", "b", "c"] share the same type, while [1, 2, 3] and "abc" do not.

In Python, we can easily compare types using the built-in type function. This function returns the type of the object as class.

a = 5
print(type(a))   #outputs <class 'int'>

We can use this to compare types of two different object. Let’s see an example.

Use type() to Compare Types

Call type(obj) to return the type of obj. Use == to compare this type with another.

list_a = [1, 2, 3]
list_b = ["a", "b", "c"]

compare_lists = type(list_a) == type(list_b)


Output: True

As you can see, the type of both the objects came out to be same. Now, let’s compare two objects of different types and see its result:

a_list = [4, 2, 6]
a_string = "pqr"

compare_list_and_string = type(a_list) == type(a_string)


Output: False

As expected, their types didn’t matched so we get False as ouput.

In conclusion, you can use the type() function with the == operator to compare the types of different objects in Python programming language.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply