When you create a variable in Python, you don't have to specify its type because Python is a dynamically typed language. That means the kind of a variable is determined at runtime based on the value it's assigned. However, there are many situations where you want to know the type of a variable.
In this guide, we'll look into various ways you can determine the type of a variable in Python. We'll provide code examples, data, and explanations along the way. We also include links to external resources for further reading to help you deepen your understanding of Python's type system.
Also read: 4 Easy Ways to Check for NaN Values in Python

Method 1: Using the type() Function
The simplest way to determine a variable's type in Python is to use the built-in type() function, which tells you what kind of data the variable contains.
Code Example:
# Example of using type() function
a = 5
b = 5.0
c = "Hello, World!"
d = [1, 2, 3]
e = (1, 2, 3)
f = {'a': 1, 'b': 2}
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'>Explanation:
The type() function is very simple and easy to use. It returns the type of variable, which can help you understand the kind of data you are working with. Just keep in mind that it does not provide more detailed type checking, such as checking for subclasses.
Method 2: Using the isinstance() Function
Although type() is simple, there are situations where isinstance() comes in handy, particularly when working with inheritance. With isinstance(), you can check if an object belongs to a certain class or a subclass of that class. This can be really helpful when dealing with complex relationships between different classes.
Code Example:
# Example of using isinstance() function
a = 5
b = 5.0
c = "Hello, World!"
d = [1, 2, 3]
print(isinstance(a, int)) # Output: True
print(isinstance(b, float)) # Output: True
print(isinstance(c, str)) # Output: True
print(isinstance(d, list)) # Output: True
# Using isinstance with inheritance
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog)) # Output: True
print(isinstance(dog, Animal)) # Output: TrueExplanation:
The isinstance() function is more flexible than type() because it considers inheritance. For example, if you have a subclass, isinstance() will return True for checks against both the subclass and the parent class.
Method 3: Type Checking with type and isinstance
Both type() and isinstance() are useful in different scenarios. Let’s compare them and see when to use each.
Code Example:
# Comparison of type() and isinstance()
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
# Using type()
print(type(dog) == Dog) # Output: True
print(type(dog) == Animal) # Output: False
# Using isinstance()
print(isinstance(dog, Dog)) # Output: True
print(isinstance(dog, Animal)) # Output: TrueExplanation:
- Use type(): When you need to check if an object is exactly of a specific type and not a subclass.
- Use isinstance(): When you want to check if an object is an instance of a class or any subclass thereof.
Both methods have their use cases, but isinstance() is generally preferred for type checking because of its ability to handle inheritance hierarchies.
Method 4: Type Hints and Annotations
With the introduction of type hints in Python 3.5 and later, you can provide hints about the types of variables and function return values, improving code readability and aiding static analysis tools.
Code Example:
# Example of using type hints
def add(x: int, y: int) -> int:
return x + y
# Using the function with type hints
result = add(3, 5)
print(result) # Output: 8
# Type hinting with variables
a: int = 10
b: float = 20.5
print(type(a)) # Output: <class 'int'>
print(type(b)) # Output: <class 'float'>Explanation:
Type hints do not enforce type checking at runtime but serve as a guide for developers and tools. They can be checked using tools like mypy for static type checking.
Method 5: Advanced Type Checking with typing Module
Python's typing module provides support for type hints and helps in creating more complex types, like lists of specific types, tuples, and more.
Code Example:
from typing import List, Tuple, Dict
# Using typing for more complex types
def process_list(numbers: List[int]) -> int:
return sum(numbers)
def get_coordinates() -> Tuple[float, float]:
return 1.0, 2.0
def get_user_info() -> Dict[str, int]:
return {'age': 30, 'id': 123}
# Using the functions with typing
print(process_list([1, 2, 3])) # Output: 6
print(get_coordinates()) # Output: (1.0, 2.0)
print(get_user_info()) # Output: {'age': 30, 'id': 123}Explanation:
The typing module allows for more complex type definitions, improving the readability and maintainability of your code. It is especially useful in larger codebases where understanding data structures at a glance is beneficial.
Also read: Understanding Data Types in Python Programming
Conclusion
It's important to know the type of a variable in Python code to avoid errors, make your code easier to read, and ensure it's robust. Whether you're using type(), isinstance(), or type hints with the typing module, Python gives you various options to check and define types. By using these tools effectively, you can write code that's easier to understand and maintain.
If you want to explore this topic further, I recommend checking out the official Python documentation and joining discussions on sites like Stack Overflow. You'll find valuable information and practical examples that can help you better understand Python's type system.
Join Index.dev, the platform connecting top Python developers with remote tech companies. Access exclusive jobs in the UK, EU, and US!