0
0
Pythonprogramming~5 mins

type() and isinstance() in Python

Choose your learning style9 modes available
Introduction

We use type() and isinstance() to check what kind of thing (type) a value or object is. This helps us understand or control how our program works.

When you want to check if a number is really a number before doing math.
When you want to make sure a variable is a list before looping over it.
When you want to treat different types of data differently in your program.
When debugging to see what type of data you have.
When writing functions that accept different types and you want to handle them safely.
Syntax
Python
type(object)
isinstance(object, classinfo)

type(object) returns the exact type of the object.

isinstance(object, classinfo) checks if the object is an instance of the classinfo or its subclasses.

Examples
Shows the type of an integer, a string, and a list.
Python
type(5)
type('hello')
type([1, 2, 3])
Checks if the values are instances of int, str, and list respectively.
Python
isinstance(5, int)
isinstance('hello', str)
isinstance([1, 2, 3], list)
Returns True because in Python, bool is a subclass of int.
Python
isinstance(True, int)
Both check if 5 is an integer, but isinstance is more flexible with subclasses.
Python
type(5) == int
isinstance(5, int)
Sample Program

This program prints the type of the value using type() and then uses isinstance() to print a friendly message about what kind of data it is.

Python
def check_type(value):
    print(f'Value: {value}')
    print(f'type(): {type(value)}')
    if isinstance(value, int):
        print('This is an integer.')
    elif isinstance(value, str):
        print('This is a string.')
    elif isinstance(value, list):
        print('This is a list.')
    else:
        print('Unknown type.')

check_type(10)
check_type('hello')
check_type([1, 2, 3])
check_type(3.14)
OutputSuccess
Important Notes

type() gives the exact type, so it does not consider inheritance.

isinstance() is better when you want to allow subclasses or multiple types.

Use isinstance() for safer and more flexible type checking in most cases.

Summary

type() tells you the exact type of an object.

isinstance() checks if an object belongs to a type or its children types.

Use these to make your program understand and handle data correctly.