×

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five standard data types in Python programming language:

  1. Numeric
  2. Boolean
  3. Sets
  4. Dictionary
  5. Sequences type
    • String
    • Tuple
    • Lists

It is important to know the data type of a variable to perform operations on it. As Python is a dynamically typed language, we need not to specify the data type while declaring a variable but still, to use variables in logics, we need to know the data type.

Ways to check Data Type in Python

We can find the data type of a variable in Python using two different methods:

  1. The type () method
  2. The isinstance () method

Generally, we use the type () method more because it is designed in the Python libraries especially for this, while isinstance () method has other kinds of applications too.

  1. The type () method

We can find the data type or the class type of the variable or the object passed as an argument in the type () function at the run time.

Syntax:

  • Single argument: type (object)

It returns the data type of the specified object in the function.

  • Three arguments: type (name, base, dictionary)

It returns a new type object or a new class at run time
Here, name refers to the name of the class to be created,
base is a tuple that contains base classes for the main class,
dictionary contains the body of the class to be created.

Programs:

  • type () function with single argument

Program:

list1 = [1, 2, 3, 4, 5]

print ("The type of", list1, "is", type (list1))

string1 = "Hi!"

print ("The type of", string1, "is", type (string1))

tuple1 = (1, 2, 34)

print ("The type of", tuple1, "is", type (tuple1))

Output:

The type of [1, 2, 3, 4, 5] is <class 'list'>

The type of Hi! is <class 'str'>

The type of (1, 2, 34) is <class 'tuple'>

Explanation:

It simply specifies the type of the argument given in the function

  • type () function with three arguments

Program:

object1 = type ('X', (object,), dict (a = 'yes', b = 6))

print (type (object1))

print (vars (object1))

class test:

  a = 'yes'

  b = 6

object2 = type ('Y', (test,), dict (a = 'yes', b = 6))

print (type (object2))

print (vars (object2))

Output:

<class 'type'>

{'a': 'yes', 'b': 6, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}

<class 'type'>

{'a': 'yes', 'b': 6, '__module__': '__main__', '__doc__': None}

Explanation:

First, we used the type function with a single base class that is the object class and named it ‘X’. We used the type () function with one argument ‘X’ to return the data type which gave “type” class. The vars () function in python is used to represent the __dict__ attribute of the class.

In the second case, we gave a created base class, the test class in which we specified the body of the class.

  • The isinstance() method:

The isinstance method is much preferred because of its ability to check if the given object is an instance of the specified subclass. It takes two parameters, object and type of a class.

Syntax:

isinstance (object, class/ tuple of classes)

Return type: boolean

Mechanism:

The function returns “True” if the object which is the first argument belongs to the class as an instance specified as the second argument. If not, it returns False.

Program:

a = isinstance ("Hi", (int))

print ("Does 'Hi' belong to the integer class? ", a)

b = isinstance (5, (int, float, str, dict))

print ("Do 5 belong to any of int, float, str or dict classes?", b)

class myclass:

    name = "hardin"

x = myclass ()

y = isinstance (x, myclass)

print ("Is x an object of myclass?: ",y)

Output:

Does 'Hi' belong to the integer class?  False

Do 5 belong to any of int, float, str or dict classes? True

Is x an object of myclass?: True

Explanation:

First, we checked if the string “Hi” belongs to the integer class which does not; so we got False. Then, we checked if 5 which is an integer belongs to any of int, float, dict and string classes which it does, hence we got true. Then, we created a class “myclass” and created an object to the class x. Now, we check if x is an object to the class myclass, which it is, so we got “true”.

Type () or isinstance ()?

Mostly, people use the type () method more but it is preferred to go to the isinstance () method for many reasons:

  1. If we want to check if an object belongs to any class among a few classes, we can simply specify all the classes and get a true of false in the case of the isinstance method. But, in the type (0 method, we get true, only when we use the exact same type object on both sides.
  2. Type () method does not support the inheritance which is a core of the object oriented programming

If we just need the data type to be printed, we can use the type method but if we need to check, isinstance () method is preferred more.


Related Topics

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.

Python System Requirements

Introduction As we know, Python is a popular programming language usually used to write scripts for operating systems. It’s handy adequate for utilizing in web development and application design. In this article,...

2 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Python program to print array element present at even position

Python program to print array element present at even position In this program, we'll see a Python program that prints the elements of an array that are in even positions. We...

1 minute read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Python BytesIO

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.