How to Compare Types in Python?

Estimated read time 2 min read

To compare types in Python, you can use the type() function or the isinstance() function. Here’s how you can use each of these approaches:

  1. Using the type() function: The type() function returns the type of an object. You can compare the types of two objects using the equality (==) operator. For example:
a = 5
b = 10.5

if type(a) == type(b):
    print("Types are the same.")
else:
    print("Types are different.")

In this example, we compare the types of variables a and b using the type() function. If the types are the same, the condition type(a) == type(b) evaluates to True, and the corresponding code block is executed, printing “Types are the same.” If the types are different, the condition evaluates to False, and the else block is executed, printing “Types are different.”

  1. Using the isinstance() function: The isinstance() function checks if an object is an instance of a specified type or any of its subclasses. You can compare the types of two objects using the isinstance() function. For example:
a = 5
b = 10.5

if isinstance(a, type(b)):
    print("Types are the same.")
else:
    print("Types are different.")

In this example, we use the isinstance() function to check if a is an instance of the same type as b. If a is an instance of the same type or any subclass of that type, the condition isinstance(a, type(b)) evaluates to True, and the corresponding code block is executed, printing “Types are the same.” Otherwise, the condition evaluates to False, and the else block is executed, printing “Types are different.”

Choose the approach that best suits your specific use case. The type() function is useful when you want to compare the exact types of objects, while the isinstance() function allows for more flexibility by considering subclasses as well.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply