How to determine the type of an object in Python?

Better Stack Team
Updated on February 3, 2023

You can use the type() function to determine the type of an object in Python. For example:

 
x = 10
print(type(x))  # Output: <class 'int'>

y = "hello"
print(type(y))  # Output: <class 'str'>

z = [1, 2, 3]
print(type(z))  # Output: <class 'list'>

You can also use the isinstance() function to check if an object is an instance of a particular class or a subclass of it. For example:

 
x = 10
print(isinstance(x, int))  # Output: True
print(isinstance(x, str))  # Output: False

y = "hello"
print(isinstance(y, str))  # Output: True
print(isinstance(y, list))  # Output: False

z = [1, 2, 3]
print(isinstance(z, list))  # Output: True
print(isinstance(z, tuple))  # Output: False

You can also use the issubclass() function to check if a class is a subclass of another class. For example:

 
class A:
    pass

class B(A):
    pass

print(issubclass(B, A))  # Output: True
print(issubclass(A, B))  # Output: False

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github