Python isinstance()

Python isinstance() builtin function is used to check if given instance is an instance of given class or sub class of given class.

In this tutorial, we will learn about the syntax of Python isinstance() function, and learn how to use this function with the help of examples.

Syntax

The syntax of isinstance() function is

isinstance(object, classinfo)

where

ParameterRequired/OptionalDescription
objectRequiredA python object whose id has to be found out.
classinfoRequiredA class, a type, a tuple of classes, or a tuple of types.

If given object is an instance of given type or matches an item in the tuple of types, subclass, or a subclass to an item present in the tuple of types, isinstance() function returns True. Else, isinstance() function returns False.

Returns

The function returns boolean value.

Example

In this example, we will check if given object myList is an instance of a list class or not, using isinstance() builtin function.

Pass the object myList, and the type we would like to check this object against, i.e., list, to isinstance() function.

Python Program

myList = [24, 0, 8, 6]
result = isinstance(myList, list)
print(f'Is given object an instance of type list? {result}.')
Try Online

Output

Is given object an instance of type list? True.

Since, myList is object of type list, isinstance() returns True.

Now, let us take us check if myList is an object of type tuple. Since it is not, isinstance() should return False.

Python Program

myList = [24, 0, 8, 6]
result = isinstance(myList, tuple)
print(f'Is given object an instance of type list? {result}.')
Try Online

Output

Is given object an instance of type list? False.

Example – instance() with Tuple of Types

In this example, we will check if given object myList is an instance of a list, tuple or range, using isinstance() builtin function.

Pass the object myList, and the types we would like to check this object against, i.e., (list, tuple, range), to isinstance() function.

Python Program

myList = [24, 0, 8, 6]
result = isinstance(myList, (list, tuple, range))
print(f'Is given object an instance of type list? {result}.')
Try Online

Output

Is given object an instance of type list? True.

Conclusion

In this Python Tutorial, we have learnt the syntax of Python isinstance() builtin function, and also learned how to use this function, with the help of Python example programs.