Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Hosted By
Ryan Valles
Founder, Interview Kickstart
Our tried & tested strategy for cracking interviews
How FAANG hiring process works
The 4 areas you must prepare for
How you can accelerate your learnings

type() and isinstance() in Python

The type() and isinstance() functions are both fairly straightforward concepts. Every Python object (like pythonObject) has a built-in or custom data type associated with it. The function type(pythonObject) returns the data type associated with the object passed as the argument. The function isinstance(pythonObject, dataType), on the other hand, returns True or False, based on whether the object passed is an instance of the provided data type or not. This article explores both type() and isinstance() in detail.

If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Python String join() Method, Sum Function in Python, and How to Read and Write Files in Python for more specific insights and guidance on Python concepts and coding interview preparation.

Having trained over 9,000 software engineers, we know what it takes to crack the toughest tech interviews. Since 2014, Interview Kickstart alums have been landing lucrative offers from FAANG and Tier-1 tech companies, with an average salary hike of 49%. The highest ever offer received by an IK alum is a whopping $933,000!

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview? Sign up for our FREE Webinar.

In this article, we’ll discuss:

  • What Is type() in Python?
  • What Is isinstance() in Python?
  • type() in Python: Syntax and Examples
  • isinstance() in Python: Syntax and Example
  • type() vs. isinstance() in Python
  • FAQs on type() and isinstance() in Python

What Is type() in Python?

The type() method is a built-in function in Python that can take either a single argument or three arguments. When type() takes a single argument, it returns the class the passed argument belongs to. The argument can be a variable or an object.

When type() takes three arguments, it returns a new type of object. The arguments are the name of the class, the base class (optional), and a dictionary that holds the namespaces for the class (optional).

What Is isinstance() in Python?

The isinstance() method is a built-in function in Python that takes two arguments: an object/variable and a class/data type. The isinstance() function checks if the object passed is an instance of the class provided in the argument or not. If yes, it returns True; otherwise, it returns false.

type() in Python: Syntax and Examples

As discussed, type() in Python can be used in two ways:

We’ll now look at the syntax of type() and use it in an example to understand it better.

type() Syntax

type(pythonObject)

type(className, baseClass, dict)

type() Example With Single Argument

Example:

intExample = 1331

floatExample = 1.234

complexnumExample = 5j+100

stringExample = "Interview Kickstart"

listExample = ["L", "I", "S", "T"]

tupleExample = ("T", "U", "P", "L", "E")

setExample = {'S', 'E', 'T'}

dictExample = {"Apple":"a", "Banana":"b", "Chocolate":"c", "Dragonfruit":"d"}


print("The data type/class of intExample is: ",type(intExample))

print("The data type/class of floatExample is: ",type(floatExample))

print("The data type/class of complexnumExample is: ",type(complexnumExample))

print("The data type/class of stringExample is: ",type(stringExample))

print("The data type/class of listExample is: ",type(listExample))

print("The data type/class of tupleExample is: ",type(tupleExample))

print("The data type/class of setExample is: ",type(setExample))

print("The data type/class of dictExample is: ",type(dictExample))


# We can also do it for an object of a user defined class

class userDefCoordinateExample(object):

def __init__(self):

name =""

age = 0

positionBall = userDefCoordinateExample()

print("The data type/class of positionBall is: ",type(positionBall))

Output:

The data type/class of intExample is:  <class 'int'>

The data type/class of floatExample is:  <class 'float'>

The data type/class of complexnumExample is:  <class 'complex'>

The data type/class of stringExample is:  <class 'str'>

The data type/class of listExample is:  <class 'list'>

The data type/class of tupleExample is:  <class 'tuple'>

The data type/class of setExample is:  <class 'set'>

The data type/class of dictExample is:  <class 'dict'>

The data type/class of positionBall is:  <class '__main__.userDefCoordinateExample'>

type() Example With Three Arguments

Example:

class dataTypeExample:

intExample = 1331

listExample = ["L", "I", "S", "T"]

typeReturns = type('newClassCreation', (dataTypeExample,), dict(intExample = 1331, listExample = ["L", "I", "S", "T"]))


#Printing the type of value returned by type above

print(type(typeReturns))


print("\n")


#Printing the dict attribute of the object typeReturns

print(vars(typeReturns))


Output:

<class 'type'>

{'intExample': 1331, 'listExample': ['L', 'I', 'S', 'T'], '__module__': '__main__', '__doc__': None}


isinstance() in Python: Syntax and Example

isinstance() in Python has the following characteristics in terms of arguments and return value:

An important functionality of isinstance() is also that it supports inheritance, making it one of the main differentiating points between type() and isinstance(). For example, consider the code below:

Code:

class A():

def _init_(self):

self.a = 10


class B(A):

def _init_(self):

self.b = 100



B_obj = B()

print(isinstance(B_obj, A))


Output:

True

The output for this code is “True” as B_obj is an instance of class-B, which is inheriting its properties from class-A.

Syntax

isinstance(pythonObject, className)

isinstance() Example Using list, dict, set, string in Python

Example:

intExample = 1331

floatExample = 1.234

complexnumExample = 5j+100

stringExample = "Interview Kickstart"

listExample = ["L", "I", "S", "T"]

tupleExample = ("T", "U", "P", "L", "E")

setExample = {'S', 'E', 'T'}

dictExample = {"Apple":"a", "Banana":"b", "Chocolate":"c", "Dragonfruit":"d"}


print("Is the data type/class of intExample int?: ",isinstance(intExample, int))

print("Is the data type/class of floatExample float?: ",isinstance(floatExample, float))

print("Is the data type/class of complexnumExample complex?: ",isinstance(complexnumExample, complex))

print("Is the data type/class of stringExample str?: ",isinstance(stringExample, str))

print("Is the data type/class of listExample list?: ",isinstance(listExample, list))

print("Is the data type/class of tupleExample tuple?: ",isinstance(tupleExample, tuple))

print("Is the data type/class of setExample set?: ",isinstance(setExample, set))

print("Is the data type/class of dictExample dict?: ",isinstance(dictExample,dict))


Output:

Is the data type/class of intExample int?:  True

Is the data type/class of floatExample float?:  True

Is the data type/class of complexnumExample complex?:  True

Is the data type/class of stringExample str?:  True

Is the data type/class of listExample list?:  True

Is the data type/class of tupleExample tuple?:  True

Is the data type/class of setExample set?:  True

Is the data type/class of dictExample dict?:  True

Type() vs. Isinstance() in Python

One of the main differentiating factors between type() and isinstance() is that the type() function is not capable of checking whether an object is an instance of a parent class, whereas isinstance() function is capable of doing so.

In other words, isinstance() supports inheritance, whereas type() doesn't.

FAQs on type() and isinstance() in Python

1.  Should I use isinstance() or type() in Python? Why?

Isinstance() is faster than type(), and it also considers inheritance. In other words, it recognizes that an instance of a derived class is an instance of the base class as well. That is why we often prefer isinstance() over type().

2. What is the difference between isinstance() and type() in Python?

Isinstance() tells you whether the object passed is an instance of the class passed as an argument or not, while type() simply tells you the class of the object passed.

3. Are there any concerns associated with using isinstance in Python? 

The concern with isinstance() is that it creates forks in the code, and the result is sensitive to how the class definitions were imported, where the object was instantiated, and where the isinstance() test was done. That said, isinstance() is appropriate for some types of tasks, like finding out if a variable is an int or not.

4. How do you check if something is an integer in Python?

For a variable isItInt, you can: (a) Use isinstance() as shown below along with int as the class argument, and if the result is True, the variable is an integer: isinstance(isItInt, int). (b) Use type() as shown below, and if the result is <class ‘int’> then the variable is an integer: type(isItInt)

5. Does isinstance() work for subclasses?

Yes, since isinstance() takes into account inheritance, it recognizes that an instance of a subclass is an instance of the base class as well, and hence, it works for subclasses too.

Ready to Nail Your Next Coding Interview?

Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, a Tech Lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!


Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Hosted By
Ryan Valles
Founder, Interview Kickstart
Our tried & tested strategy for cracking interviews
How FAANG hiring process works
The 4 areas you must prepare for
How you can accelerate your learnings

Recommended Posts

All Posts