0% found this document useful (0 votes)
81 views

Python Isinstance With Examples (Guide)

Uploaded by

Agus Suwardono
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Python Isinstance With Examples (Guide)

Uploaded by

Agus Suwardono
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Python isinstance() With Examples [Guide] https://pynative.

com/python-isinstance-explained-with-examples/

PYnative
Python Programming
 Learn Python  Exercises  Quizzes  Code Editor  Tricks

Home » Python » Python isinstance() function


Posted In
explained with examples
Python Python Basics

Tweet F  share in  share P  Pin Python isinstance()


function explained
   Python Tutorials
with examples
 Get Started with Python
Updated on: June 29, 2021 | + 11 Comments
 Python Statements

 Python Comments The Python’s isinstance() function checks


 Python Keywords whether the object or variable is an instance of
 Python Variables the specified class type or data type.
 Python Operators
For example, isinstance(name, str) checks if
 Python Data Types
name is an instance of a class str .
 Python Casting

 Python Control Flow statements


Also, Solve: Python Basic Exercise and
 Python For Loop
Beginners Quiz
 Python While Loop

 Python Break and Continue

 Python Nested Loops

 Python Input and Output


Table of contents
 Python range function
• How To Use isinstance() Function in Python
 Check user input is String or
• Example
Number
• isinstance() With Built-In Types
 Accept List as a input from user
• isinstance() With Multiple Classes
 Python Numbers
• isinstance() With Python Class
 Python Lists
• isinstance() function With Inheritance
 Python Tuples
• isinstance with Python list
 Python Sets
• Checking if an object is an instance of a
 Python Dictionaries
list type
 Python Functions
• Check if an element of a list is a nested
 Python Modules
list
 Python isinstance()
• Check if elements of a list are numbers
 Python Object-Oriented or strings
Programming
• Next steps
 Python Exceptions

 Python Exercise for Beginners

 Python Quiz for Beginners

All Python Topics

Python Basics Python Exercises


Python Quizzes
Python File Handling Python OOP
Python Date and Time

1 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming How To Use
Learn isinstance()
Python  Exercises  Quizzes  Code Editor  Tricks

Function in Python

Let’s see the syntax first before moving to the


example.

Syntax:

isinstance(object

• It takes two
Python isinstance()
arguments, and
both are
mandatory.

• The
isinstance()
function checks
if the object
argument is an
instance or
subclass of
classinfo class
argument

Using isinstance() function, we can test


whether an object/variable is an instance of the
specified type or class such as int or list. In the
case of inheritance, we can checks if the specified
class is the parent class of an object.

1. Pass object to isinstance()

Pass the variable you want to check as


object argument to the isinstance() .
Here the object can be any class object or
any variable name

2. Specify the Class or Type name as a


classinfo argument

2 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
For example, isinstance(x, int) to check
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
if x is an instance of a class int .
classinfo is a type name or Class name
you want to check against the variable. Here
you can specify data type name or Class
name.
You can also pass multiple classes/types in a
tuple format. For example, you can pass
int , str , list , dict , or any user-created
class.

3. Execute your operation, If result is


True

The isinstance() returns True if an object


or variable is of a specified type otherwise
False.

Example

Using isintance() we can verify whether a variable


is a number or string. Let’s assume variable num
= 90 , and you want to check whether num is an
instance of an int type.

num = 90
result = isinstance(num, int)
if result:
print("Yes")
else:
print("No")

   Run

Output:

Yes

As we can see in the output, the isinstance()


returned True because num hold an integer
value.

3 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Note: If the classinfo argument is not a
Class, type, or tuple of types, a TypeError
exception is raised.

isinstance() With Built-In


Types
As you know, Every value (variable) in Python has
a type. In Python, we can use different built-in
types such as int , float , list, tuple, strings,
dictionary. Most of the time, you want to check
the type of value to do some operations. In this
case, isinstance() function is useful.

# Check if 80 is an instance of class int


number = 80
print(isinstance(number, int))
# output True

print(isinstance(number, float))
# output False

pi = 3.14
# Check 3.14 is an instance of class float
print(isinstance(pi, float))
# Output True

# Check if (1 + 2j) is an instance of complex


complex_num = 1 + 2j
print(isinstance(complex_num, complex))
# Output True

# Check if 'PYnative' is an instance of class string


name = "PYnative.com"
print(isinstance(name, str))
# Output True

# Check if names is an instance of class list


names = ["Eric", "Scott", "Kelly"]
print(isinstance(names, list))
# Output True

# Check if student_report is an instance of class dict


student_report = {"John": 80, "Eric": 70,

4 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
print(isinstance(student_report, dict))
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
# Output True

# Check if names is an instance of class tuple


names = ("Sam", "Kelly", 'Emma')
print(isinstance(names, tuple))
# Output True

# Check if numbers is an instance of class tuple


numbers = {11, 22, 33, 44, 55}
print(isinstance(numbers, set))
# Output True

   Run

Note: If we use the isinstance() with any


variable or object with a None , it returns False .
Let see the simple example of it.

var = None
# empty but not None
s1 = ''
print(isinstance(var, float))
# Output False
print(isinstance(s1, str))
# Output True

   Run

isinstance() With Multiple


Classes
You can also check the instance with multiple
types. Let’s say you have a variable, and you
wanted to check whether it holds any numeric
value or not, for example, a numeric value can be
an int or float .

5 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
 Learn Python  Exercises  Quizzes  Code Editor  Tricks

To verify whether a variable is an instance of one


of the specified types, we need to mention all
types in a tuple and pass it to the classInfo
argument of isinstance() .

Example

def check_number(var):
if isinstance(var, (int, float)):
print('variable', var, 'is instance of numeric type
else:
print('variable', var, 'is not instance of numeric

num1 = 80
check_number(num1)
# Output variable 80 is instance of numeric type

num2 = 55.70
check_number(num2)
# Output variable 55.7 is instance of numeric type

num3 = '20'
check_number(num3)
# Output variable '20' is not instance of numeric type

   Run

isinstance() With Python


Class
The isinstance() works as a comparison
operator, and it compares the object with the
specified class type.

You can verify if the emp object is an instance of a


user-defined class Employee using the
isinstance() function. It must return True.

class Employee:

def __init__(self, name, salary):


self.name = name

6 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
self.salary = salary
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
class Person:

def __init__(self, name, sex):


self.name = name
self.sex = sex

emp = Employee("Emma", 11000)


per = Person("Brent", "male")

# Checking if a emp object is an instance of Employee


print(isinstance(emp, Employee))
# Output True

# Checking if the per object is an instance of Employee


print(isinstance(per, Employee))
# Output False

   Run

isinstance() function With


Inheritance
The object of the subclass type is also a type of
parent class. For example, If Car is a subclass of a
Vehicle, then the object of Car can be referred to
by either Car or Vehicle. In this case, the
isinstance(carObject, Vehicle) will return
True .

The isinstance() function works on the


principle of the is-a relationship. The concept of
an is-a relationship is based on class inheritance.

The instance() returns True if the classinfo


argument of the instance() is the object’s class’s
parent class.

To demonstrate this, I have created two classes,


Developer and PythonDeveoper. Here
PythonDeveoper is a sub-class of a Developer
class.

7 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
class  Learn Python  Exercises
Developer(object):  Quizzes  Code Editor  Tricks

# Constructor
def __init__(self, name):
self.name = name

def display(self):
print("Developer:", self.name, "-"

class PythonDeveloper(Developer):

# Constructor
def __init__(self, name, language):
self.name = name
self.language = language

def display(self):
print("Python Developer:", self.name

# Object of PythonDeveloper
dev = PythonDeveloper("Eric", "Python")
# is PythonDeveloper object an instance of a PythonDevelope
print(isinstance(dev, PythonDeveloper))
# Output True

# is python_dev object an instance of a Developer Class


print(isinstance(dev, Developer))
# Output True

   Run

Note: The isinstance() function is beneficial


for casting objects at runtime because once you
get to know the given class is a subclass of a
parent class, you can do casting appropriately if
required.

isinstance with Python list


As you know, a Python list is used to store
multiple values at the same time. These values
can be of any data type like numbers, strings, or
any Class objects.

In this section, we will test the following


operations with the Python list using the

8 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
isinstance() function:
 Learn Python  Exercises  Quizzes  Code Editor  Tricks

• Checking if an object is of type list in


python.

• Check if an element of a list is a list.

• Verify if elements of a list are numbers or


strings.

• Python check if all elements of a list are the


same type

Checking if an object is an
instance of a list type

sample_list = ["Emma", "Stevan", "Brent"]


res = isinstance(sample_list, list)
print(sample_list, 'is instance of list?'

# Output 'Emma', 'Stevan', 'Brent'] is instance of list? Tr

   Run

Check if an element of a list is a


nested list

To check if one of the elements in the list is itself


a list. For example, you have the following list,
Use the isinstance() to verify if the list contains
a nested list

sampleList = ['Emma', 'Stevan', ['Jordan'

Iterate a list and verify each element’s class, and if


it a list type, we can say that the list contains a
nested list.

sample_list = ['Emma', 'Stevan', ['Jordan'


for item in sample_list:
if isinstance(item, list):
print("Yes", item, 'is a nested list'

9 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
# Output Yes ['Jordan', 'Donald', 'Sam'] is a nested list
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
   Run

Check if elements of a list are


numbers or strings

Check each element’s type with multiple numeric


types such as int , float , and complex using
the isinstance() function.

To find all string variables, Check each element’s


type with str type.

sample_list = ['Emma', 'Stevan', 12, 45.6


number_list = []
string_list = []
for item in sample_list:
if isinstance(item, (int, float, complex
number_list.append(item)
elif isinstance(item, str):
string_list.append(item)

# String List
print(string_list)
# Output ['Emma', 'Stevan', 'Eric']

# Number list
print(number_list)
# Output [12, 45.6, (1+2j)]

   Run

Next steps

10 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
Let me know your comments and feedback in the
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
section below.

Solve:

• Python exercise for beginners

• Python Quiz for beginners

Filed Under: Python , Python Basics

Did you find this page helpful? Let others know


about it. Sharing helps me continue to create
free Python resources.

Tweet F  share in  share P  Pin

About Vishal

Founder of PYnative.com I am a
Python developer and I love to
write articles to help
developers. Follow me on Twitter. All the best
for your future Python endeavors!

Related Tutorial Topics:

Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python


basics, data structure, data analytics, and more.

15+ Topic-specific
Exercises
Exercises and
Quizzes

11 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative Each Exercise


 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming Quizzes
contains 10
questions
Each Quiz contains
12-15 MCQ

Comments

ZAINAB says
JA NUA R Y 1 5 , 2 0 2 2 AT 7 : 4 6 P M

‘you are just fabulous bro, appreciating


your work is a right of mine,

REPLY

Gowsia Zargar says


JA NUA R Y 3 , 2 0 2 1 AT 6 : 1 4 P M

Your articles are very helpful in


understanding python concepts are
they are written in a simpler form
which makes coding fun.

REPLY

Vishal says
JA NUA R Y 7 , 2 0 2 1 AT
10:07 AM

Thank you, Gowsia.

REPLY

Spoorthi says
O C TO B E R 1 3 , 2 0 2 0 A T 5 : 1 5 A M

I’m a beginner and I dont have any


programming knowlde but I love to
learn Python!. Simple and crystal
clear!,. Appreciate it!.

REPLY

Vishal says
O C TO B E R 1 6 , 2 0 2 0 A T
4:45 PM

Thank you, Spoorthi

REPLY

12 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative
Python Programming
Alberta says
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
J U LY 1 7 , 2 0 2 0 A T 1 2 : 1 5 A M

This is great! Self-explanatory. Good


work!

REPLY

Vishal says
J U LY 2 0 , 2 0 2 0 A T 1 : 1 6 P M

Thank you, Alberta.

REPLY

peter says
JUNE 1 4 , 2 0 2 0 AT 9 : 1 5 P M

simply understood. thank you so much

REPLY

deborgher says
M AY 2 5 , 2 0 2 0 AT 9 : 0 7 P M

I am learning Python and explore any


document or help, as I am very curious.
Thanks Vishal for this excellent and
very interesting article

REPLY

Handy says
M AY 2 4 , 2 0 2 0 AT 9 : 2 3 P M

Great articles!! I got a lot insights


through your articles. Your contents
are clear easy and relevant; with
concrete and simple examples. I grab a
lot on the use of isinstance() function
in python. Thanks for sharing!

REPLY

Vishal says
M AY 2 5 , 2 0 2 0 AT 4 : 0 1 P M

You are welcome, Handy

REPLY

Leave a Reply

13 of 14 12/20/2022, 4:19 PM
Python isinstance() With Examples [Guide] https://pynative.com/python-isinstance-explained-with-examples/

PYnative your email address will NOT be published. all


 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming comments are moderated according to our comment
policy.

Comment *

Use <pre> tag for posting code. E.g. <pre> Your


code </pre>

Name * Email *

Post Comment

About PYnative Explore Python Follow Us Legal Stuff

PYnative.com is for Python • Learn Python To get New Python Tutorials, • About Us
lovers. Here, You can get • Python Basics Exercises, and Quizzes • Contact Us
Tutorials, Exercises, and
• Python Databases • Twitter We use cookies to improve
Quizzes to practice and
• Python Exercises your experience. While using
improve your Python skills. • Facebook
PYnative, you agree to have
• Python Quizzes • Sitemap
read and accepted our Terms
• Online Python Code Editor
Of Use, Cookie Policy, and
• Python Tricks Privacy Policy.

Copyright © 2018–2022
pynative.com

AN ELITE CAFEMEDIA TECH PUBLISHER

14 of 14 12/20/2022, 4:19 PM

You might also like