×

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

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 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.

Python pynmea2

Define Pynmea2 Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in...

4 minutes read.

Dynamic Typing in Python

Many key factors for developing a great programming language include how it manages its memory space. This memory space largely depends on empty memory boxes called variables that one creates...

3 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Permutations in Python

Recursion Basic idea: for numbers of length N. N-1 items are chosen at random between 0 and then generate permutations using the remaining N-1 elements in a recursive fashion. Once you've done...

4 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Python Interpreter

In this tutorial, we will go through the basic knowledge about what an interpreter is and how we use it in the python programming language. It is one of the...

3 minutes read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

1 minute read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.