How to Check Data Type in Python

Here are two ways to check data type in Python:

  1. Using type()
  2. Using isinstance()

Method 1: Using type()

The type() method returns the type object of the argument passed to it.

For example, type(“Chat”) will return “str” because it is a string literal.

Syntax

type(object)

Parameters

object: It is required; it can be a string, integer, list, tuple, set, dictionary, float, etc.

Visual Representation

How to Use type() function in Python

Example

str = 'AppDividend'
print(type(str))

int = 123
print(type(int))

float = 21.19
print(type(float))

negative = -19
print(type(negative))

dictionary = {'blog':'AppDividend'}
print(type(dictionary))

list = [1, 2, 3]
print(type(list))

tuple = (19, 21, 46)
print(type(tuple))

Output

<class 'str'>
<class 'int'>
<class 'float'>
<class 'int'>
<class 'dict'>
<class 'list'>
<class 'tuple'>

Method 2: Using isinstance()

The isinstance() is used to check if an object is an instance of a specified class or of a subclass thereof, and returns True or False.

Syntax

isinstance(object, classinfo)

Parameters

object: The object to be checked.

classinfo: A class, type, or a tuple of classes and types.

Visual Representation

Using an isinstance() function

Example

a_str = 'AppDividend'
b_int = 123
c_float = 21.19
d_negative = -19
e_dictionary = {'blog':'AppDividend'}
f_list = [1, 2, 3]
g_tuple = (19, 21, 46)

print(isinstance(a_str, str))
print(isinstance(b_int, int))
print(isinstance(c_float, float))
print(isinstance(d_negative, int))
print(isinstance(e_dictionary, dict))
print(isinstance(f_list, list))
print(isinstance(g_tuple, tuple))

Output

True
True
True
True
True
True
True

Using with Multiple Types

You can also check against multiple types at once.

number_or_float = 2.72

print(isinstance(number_or_float, (int, float)))

Output

True

Difference Between type() Function and isinstance() Function

isinstance() function type() function
It is used to check if an object is an instance of a class or a subclass thereof. It is used for checking the exact type of an object.
It takes two arguments. It takes one argument.
Returns a Boolean value(True or False). Returns a type object, which represents the object’s type.

Example

class Car:
 pass

class EVCar(Car):
 pass

# Create an instance of EVCar
new_car = EVCar()

# Using type() to check
print(type(new_car) == Car)   # new_car is an instance of EVCar, not directly Car
print(type(new_car) == EVCar) # new_car is exactly an EVCar instance

# Using isinstance() to check
print(isinstance(new_car, Car))   #EvCar is a subclass of Car
print(isinstance(new_car, EVCar)) #new_car is a EVCar instance

Output

False
True
True
True

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.