Python Mastery – From Basics to Brilliance / Python Fundamentals

Type checking - type() and isinstance()

🔍 Type Checking in Python

Type checking means finding out what type of data a value or variable contains.

Python provides two common ways to do this:

  • type()

  • isinstance()


1️⃣ type()

The type() function tells us the exact type of a value.

x = 10

print(type(x))
<class 'int'>

Examples

print(type(10))          # <class 'int'>
print(type(3.14))        # <class 'float'>
print(type("Python"))    # <class 'str'>
print(type(True))        # <class 'bool'>
print(type([1, 2, 3]))   # <class 'list'>

You can also use it to compare types:

x = 10

print(type(x) == int)    # True
print(type(x) == str)    # False

2️⃣ isinstance()

isinstance() checks whether a value belongs to a particular type.

Syntax

isinstance(value, type)

Example:

x = 10

print(isinstance(x, int))   # True
print(isinstance(x, str))   # False

Multiple Types

You can check multiple types at once:

x = 10

print(isinstance(x, (int, float)))  # True

This returns True if x is either an int or a float.


⚖️ type() vs isinstance()

type()

isinstance()

Returns the exact type

Checks whether a value is an instance of a type

type(x) == int

isinstance(x, int)

Useful for finding the type

Useful for type checking

Doesn't account for inheritance

Works with inheritance

⭐ Remember

type(x)

👉 "What exactly is the type of x?"

isinstance(x, int)

👉 "Is x an integer?"