Python isinstance() method
Last Updated :
16 Nov, 2023
Python isinstance() function returns True if the object is of specified types, and if it does not match then returns False. In this article we will see how isinstance() method works in Python
Example
Input: isinstance([1, 2, 3], list)
Output: True
Explanation: The first parameter passed is of list type.
Input: isinstance(10, str)
Output: False
Explanation: The first parameter, 10 is an integer and not a string.
Python isinstance() Function Syntax
The isinstance() method in Python has the following syntax:
Syntax:
isinstance(obj, class)
Parameters :
- obj : The object that need to be checked as a part of class or not.
- class : class/type/tuple of class or type, against which object is needed to be checked.
Returns : True, if object belongs to the given class/type if single class is passed or any of the class/type if tuple of class/type is passed, else returns False.
TypeError: if anything other than mentioned valid class type.
How instance() Function works in Python?
In Python, the instance() method works like a comparison operator. It takes two arguments, one is a Python object and the other is a class type. It compares the object with a specified type of class or a subclass and returns a boolean value, that is either True or False.
Python3
numbers = [1, 2, 3, 4, 2, 5]
result = isinstance(numbers, list)
if result:
print("The variable 'numbers' is an instance of a list.")
else:
print("The variable 'numbers' is not an instance of a list.")
|
Output
The variable 'numbers' is an instance of a list.
Examples of isinstance() Method in Python
We can provide a single class type or a Python tuple of classes to the instance() method. In the case of a tuple, the instance() method checks for all the elements in the tuple and returns True if the object is an instance of any one of the elements of the tuple, else it returns False. Let us see a few examples of the Python instance() method.
Python isinstance with Int and List
In this example, we will see how the isinstance() method work with an Integer datatype and with Python List. We check if the integer and the list are an instance of an Integer or of String type.
Python3
test_int = 5
test_list = [1, 2, 3]
print("Is test_int integer? : " + str(isinstance(test_int, int)))
print("Is test_int string? : " + str(isinstance(test_int, str)))
print("Is test_list integer? : " + str(isinstance(test_list, int)))
print("Is test_list list? : " + str(isinstance(test_list, list)))
print("Is test_int integer or list or string? : "
+ str(isinstance(test_int, (int, list, str))))
|
Output
Is test_int integer? : True
Is test_int string? : False
Is test_list integer? : False
Is test_list list? : True
Is test_int integer or list or string? : True
Demonstrating the use of isinstance() with Objects
In this example, we will check an object’s class in Python i.e, if an object is an instance of a class or its derived class.
Python3
class gfg1:
a = 10
class gfg2(gfg1):
string = 'GeeksforGeeks'
obj1 = gfg1()
obj2 = gfg2()
print("Is obj1 instance of gfg1? : " + str(isinstance(obj1, gfg1)))
print("Is obj2 instance of gfg2? : " + str(isinstance(obj2, gfg2)))
print("Is obj1 instance of gfg2? : " + str(isinstance(obj1, gfg2)))
print("Is obj2 instance of gfg1? : " + str(isinstance(obj2, gfg1)))
|
Output
Is obj1 instance of gfg1? : True
Is obj2 instance of gfg2? : True
Is obj1 instance of gfg2? : False
Is obj2 instance of gfg1? : True
Python isinstance() with String
In this example, we will use the isinstance() function with a Python String and check an object’s class in Python.
Python3
test_str = "GeeksforGeeks"
print ("Is test_str string? : " + str(isinstance(test_str, str)))
|
Output
Is test_str string? : True
Python isinstance() with Dictionary
Python isinstance() method also works with a dictionary object and check an object’s class in Python.
Python3
test_dict = {"apple" : 1, "Ball" : 2 }
print ("Is test_str dictionary? : " + str(isinstance(test_dict, dict)))
|
Output
Is test_str dictionary? : True
Python isinstance with Class Methods
In this example, we use the isinstance() method to check the value returned by a class function with a specified type and check an object’s class in Python.
Python3
class geeks:
course = 'DSA'
def purchase(obj):
return obj.course
geeks.purchase = classmethod(geeks.purchase)
str(isinstance(geeks.purchase(), str))
|
Output
True
Difference between isinstance() and type() Methods in Python
The following table demonstrates the differences between the isinstance() method and the type() method in Python.
| Syntax: isinstance(object, class) |
Syntax: type(object) |
|
It checks if an object is of a specific class type
|
It returns the class type of an object
|
|
It can check if the object belongs to a class and its subclasses
|
It cannot deal with inheritance
|
| It is faster as compared to type() |
It is slower than isinstance() |
| It returns either True or False |
It returns the type of the object |
| It can check for multiple classes at a time |
It cannot do this |
| Example: isinstance(10, (int, str)) |
Example: type(10) |
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its robust performance and powerful libraries. To get into these companies and organizations as a Python developer, we need to master some important
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Support Vector Machine (SVM) Algorithm
Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. While it can handle regression problems, SVM is particularly well-suited for classification tasks. SVM aims to find the optimal hyperplane in an N-dimensional space to separate data
10 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read