Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to check data type in Python

Introduction

When learning programming, especially in Python, it's crucial to understand data types. Data types are essential because they determine the kind of values that can be stored in a variable and the operations that can be performed on them. In this blog, we will learn how to check the data type of an object in Python.

Before we dive in, let's talk about some common data types in Python. Python has several built-in data types, such as:

  • Integers (int): These are whole numbers (e.g., 42, -7, 0)
  • Floating-point numbers (float): These are decimal numbers (e.g., 3.14, -0.01, 6.0)
  • Strings (str): These are sequences of characters (e.g., "Hello, World!", "Python")
  • Lists (list): These are ordered, mutable collections of objects (e.g., [1, 2, 3], ["apple", "banana", "cherry"])
  • Tuples (tuple): These are ordered, immutable collections of objects (e.g., (1, 2, 3), ("apple", "banana", "cherry"))
  • Dictionaries (dict): These are unordered collections of key-value pairs (e.g., {"name": "John", "age": 30})

Now that we have a basic understanding of data types, let's explore different ways to check the data type of an object in Python.

Method 1: Using the type() Function

The simplest way to check the data type of an object in Python is to use the built-in type() function. This function returns the data type of the given object.

Here's an example:

a = 42
b = 3.14
c = "Hello, World!"
d = [1, 2, 3]
e = (1, 2, 3)
f = {"name": "John", "age": 30}

print(type(a))  # Output: <class 'int'>
print(type(b))  # Output: <class 'float'>
print(type(c))  # Output: <class 'str'>
print(type(d))  # Output: <class 'list'>
print(type(e))  # Output: <class 'tuple'>
print(type(f))  # Output: <class 'dict'>

In the example above, the type() function returns the data type of each object, and we can see the output displayed as <class 'data_type'>.

Method 2: Using the isinstance() Function

Another way to check the data type of an object is to use the built-in isinstance() function. This function checks if a given object is an instance of the specified data type(s) and returns True or False.

Here's an example:

a = 42
b = 3.14
c = "Hello, World!"
d = [1, 2, 3]
e = (1, 2, 3)
f = {"name": "John", "age": 30}

print(isinstance(a, int))       # Output: True
print(isinstance(b, float))     # Output: True
print(isinstance(c, str))       # Output: True
print(isinstance(d, list))      # Output: True
print(isinstance(e, tuple))     # Output: True
print(isinstance(f, dict))      # Output: True
print(isinstance(a, (int, str))) # Output: True

In the example above, the isinstance() function checks if each object is an instance of the specified data type(s). The last example demonstrates that isinstance() can also check if an object is an instance of any of the given data types (in this case, int or str).

Method 3: Using Comparison with type()

While the isinstance() function is recommended for most use cases, sometimes you may want to compare the data type of an object directly using the type() function. This method is useful when you need to check the exact data type of an object and not its subclasses.

Here's an example:

a = 42
b = 3.14
c = "Hello, World!"
d = [1, 2, 3]
e = (1, 2, 3)
f = {"name": "John", "age": 30}

print(type(a) == int)     # Output: True
print(type(b) == float)   # Output: True
print(type(c) == str)     # Output: True
print(type(d) == list)    # Output: True
print(type(e) == tuple)   # Output: True
print(type(f) == dict)    # Output: True

In the example above, we compare the data type of each object with the desired data type using the == operator. If the data types match, the result is True, otherwise, it's False.

Understanding the Differences Between type() and isinstance()

In most cases, using the isinstance() function is the preferred method for checking the data type of an object in Python. The main reason for this is that isinstance() can handle inheritance and check for subclasses, while the type() function only checks for the exact data type.

Let's consider the following example to understand this better:

class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()

print(type(dog) == Animal)         # Output: False
print(type(dog) == Dog)            # Output: True
print(isinstance(dog, Animal))     # Output: True
print(isinstance(dog, Dog))        # Output: True

In the example above, we have two classes: Animal and Dog. The Dog class inherits from the Animal class. When we create an instance of the Dog class and use the type() function to compare its data type with the Animal class, the result is False. However, when we use the isinstance() function, it correctly identifies that the dog object is an instance of both the Animal and Dog classes.

This demonstrates the advantage of using isinstance() over type() when checking data types, especially when dealing with inheritance and subclasses.

Conclusion

In this blog, we learned different ways to check the data type of an object in Python, including using the type() function, the isinstance() function, and comparing the data type directly with the type() function. We also discussed the differences between type() and isinstance() and why isinstance() is generally the preferred method for checking data types, especially when dealing with inheritance and subclasses.

Understanding data types and how to check them is an essential skill for any Python programmer. With this knowledge, you'll be better equipped to work with different types of data and create more versatile and robust applications.