Skip to content

Python isinstance() Function | Check List, dict, int, array, etc

  • by

Python isinstance() function is used to know mid-program which objects belong to which class. If you want to know about the data type number(integer) is belongs to the int class. For that, you have to pass the 2 values in the function.

First value and second guessing class name. See below example, if its matched then result will be True else false.

a = 10

print(isinstance(a, int))

Output: True

Syntax

isinstance(object, type)

Parameter

  • Object: Required. An object to check part of a class or not.
  • Type: class/type/tuple of class or type, against which object is needed to be checked.

Return

  • True if the object is an instance or subclass of a class or any element.
  • False otherwise

1. Python isinstance list(Array), dict, int and

See the below Working example of isinstance() with Native Types:-

numbers = [11, 22, 33]

result = isinstance(numbers, list)
print(numbers,'is an instance of the list:-', result)

result = isinstance(numbers, dict)
print(numbers,'is an instance of dict:-', result)

result = isinstance(numbers, (dict, list))
print(numbers,'is an instance of dict or list:-', result)

number = 7

result = isinstance(number, list)
print(number,'is an instance of the list:-', result)

result = isinstance(number, int)
print(number,'is an instance of int:-', result)

Output:

[11, 22, 33] is an instance of the list:- True
[11, 22, 33] is an instance of dict:- False
[11, 22, 33] is an instance of dict or list:- True
7 is an instance of the list:- False
7 is an instance of int:- True

2. Demonstrating use of isinstance() with objects

class Vehicle:
    pass


class Truck(Vehicle):
    pass


print(isinstance(Vehicle(), Vehicle))

Output: True

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2019.3 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *