How to Check Data Type of Variable in Python Easily
In Python, you can check the data type of a variable using the
type() function. Just pass the variable inside type(), and it will return the variable's data type.Syntax
The syntax to check a variable's data type is simple:
type(variable): Returns the data type ofvariable.
python
type(variable)Example
This example shows how to check the data types of different variables like number, text, and list.
python
x = 10 print(type(x)) # Output: <class 'int'> name = "Alice" print(type(name)) # Output: <class 'str'> items = [1, 2, 3] print(type(items)) # Output: <class 'list'>
Output
<class 'int'>
<class 'str'>
<class 'list'>
Common Pitfalls
Sometimes beginners confuse the output of type() with just the name of the type. The type() function returns a type object, which prints with <class 'typename'>. To get just the type name as a string, use type(variable).__name__.
Also, avoid using type() to compare types with strings; use isinstance() for safer type checking.
python
x = 5 print(type(x)) # Outputs: <class 'int'> print(type(x).__name__) # Outputs: int # Safer type check if isinstance(x, int): print("x is an integer")
Output
<class 'int'>
int
x is an integer
Quick Reference
| Function | Description | Example |
|---|---|---|
| type(variable) | Returns the type object of the variable | type(10) # |
| type(variable).__name__ | Returns the type name as a string | type(10).__name__ # 'int' |
| isinstance(variable, type) | Checks if variable is of a specific type | isinstance(10, int) # True |
Key Takeaways
Use
type(variable) to find the data type of any variable in Python.The output of
type() shows the type object, not just the type name.Use
type(variable).__name__ to get the type name as a simple string.For checking types in conditions, prefer
isinstance() over comparing with type().Remember that Python data types include int, str, list, dict, and many more.