What are Python Data Types and How to Check Them
What is a data type in Python?
Think of a bookshelf containing different types of books, such as novels, textbooks, magazines, and comics. To maintain order, each type is placed in a designated section. Similarly, in Python, data types categorize and manage values, ensuring they are used appropriately in a program.
A data type in Python specifies the type of value that a variable can store. Just as a calculator is suited for numerical operations rather than reading text, specific data types are designed for certain operations. When a variable is created, Python automatically assigns a data type, making it a dynamically typed language.
Python provides several built-in data types, each serving a distinct purpose. Here’s a table highlighting some of the most common ones, along with examples:
Data Type | Description |
---|---|
Text type (str ) |
Represents a sequence of characters enclosed in quotes. Used for storing and manipulating text-based data. |
Numeric types (int , float , complex ) |
Integer (int ) holds whole numbers, float (float ) handles decimal numbers, and complex (complex ) stores numbers with a real and imaginary part. |
Sequence types (list , tuple , range ) |
List is an ordered, mutable collection, tuple is an ordered, immutable collection, and range generates sequences of numbers. |
Mapping type (dict ) |
Dictionary stores key-value pairs, allowing efficient data lookup and manipulation. |
Set types (set , frozenset ) |
Set is an unordered collection of unique elements, while frozenset is an immutable version of a set. |
Boolean type (bool ) |
Represents one of two values: True or False . Commonly used in conditions and logical operations. |
Binary types (bytes , bytearray , memoryview ) |
bytes is an immutable sequence of bytes, bytearray is a mutable byte sequence, and memoryview allows efficient manipulation of binary data without copying. |
None type (NoneType ) |
Represents the absence of a value or a null state, often used to indicate uninitialized variables or missing data. |
This image summarizes the data types in Python:
Here’s an example demonstrating these data types in Python:
# Text Typetext = "Hello, Python!"# Numeric Typesinteger_value = 42float_value = 3.14complex_value = 2 + 3j# Sequence Typesmy_list = [1, 2, 3]my_tuple = (4, 5, 6)my_range = range(1, 5)# Mapping Typemy_dict = {"name": "Alice", "age": 25}# Set Typesmy_set = {1, 2, 3}my_frozenset = frozenset([4, 5, 6])# Boolean Typeis_python_fun = True# Binary Typesbyte_data = b"hello"byte_array_data = bytearray([65, 66, 67])memory_view_data = memoryview(byte_array_data)# None Typeno_value = None
Understanding data types is essential, but verifying them programmatically ensures correct operations. To do so, let us explore Python’s type()
function.
Learn TypeScript
Learn TypeScript, a superset of JavaScript that adds types to make the language scale!Try it for freeUsing type()
function to check data types
The type()
function in Python is used to determine the data type of a value or variable. It follows this syntax:
type(variable)
Parameter:
variable
: Refers to the value or object whose type needs to be checked.
Return value:
- The function returns the class type of the given object.
Example usage of the type()
function is as follows:
print(type(42))print(type(3.14))print(type("Hello"))print(type([1, 2, 3]))print(type({"a": 1}))print(type(True))
This code results in the following output:
<class 'int'><class 'float'><class 'str'><class 'list'><class 'dict'><class 'bool'>
In each case, type()
returns the corresponding class of the provided value.
While type()
helps inspect data types quickly, it has some limitations. It only matches the exact variable type, meaning it doesn’t recognize subclasses of a parent class. Additionally, it cannot check multiple types simultaneously, making it less flexible in specific scenarios.
Python provides the isinstance()
function for a more versatile approach that supports inheritance and multiple type checks.
Using isinstance()
function to check data types
The isinstance()
function provides a more flexible way to verify data types. Unlike type()
, it allows checking whether a value belongs to a specific type or its subclasses, making it useful for object-oriented programming.
The syntax for isinstance()
is:
isinstance(variable, type)
Parameters:
variable
: Refers to the value being checked.type
: Refers to the class or a tuple of classes to check against.
Return value:
- The function returns
True
if thevariable
matches the specifiedtype
. Otherwise, it returnsFalse
.
Example usage of isinstance()
is as follows:
print(isinstance(42, int))print(isinstance(3.14, (int, float)))print(isinstance("Hello", str))print(isinstance([1, 2, 3], list))print(isinstance(True, int))
The code gives the following output:
TrueTrueTrueTrueTrue
In the example code, the isinstance()
function checks whether a variable belongs to a specified type or a tuple of types and returns the boolean values.
Note: In Python,
bool
is a subclass ofint
, soisinstance(True, int)
returnsTrue
.
While isinstance()
offers flexibility and supports inheritance, it can lead to unintended matches, like True
being recognized as an integer. Still, its ability to check multiple types makes it a preferred choice.
Checking data types is just one part of handling data effectively, and Python also allows type conversion when needed.
Converting between data types
Data must often be transformed into different types to match specific operations or requirements. Python allows data type conversion (also known as type casting) in two ways: implicit conversion and explicit conversion.
Implicit type conversion
Python automatically converts one data type to another when needed, usually promoting smaller types to larger ones to prevent data loss. An example demonstrating this is:
num_int = 10 # Integernum_float = 2.5 # Floatresult = num_int + num_floatprint(result)print(type(result))
The output produced by this code is:
12.5<class 'float'>
Here, Python automatically converts num_int
(an integer) into a float before adding, ensuring precision.
Some common implicit conversions are:
int
tofloat
int
tocomplex
bool
toint
However, implicit conversion does not occur between unrelated types like str
and int
.
Explicit type conversion
Explicit conversion requires manually converting a variable’s type using functions like int()
, float()
, str()
, list()
, and dict()
. An example of explicit type conversion is:
# Converting a float to an integernum = int(3.9)print(num)# Converting a number to a stringtext = str(100)print(text)# Converting a string to a listchars = list("hello")print(chars)# Converting a list of tuples to a dictionarypairs = [("a", 1), ("b", 2)]data_dict = dict(pairs)print(data_dict)
This code generates the following output:
3100['h', 'e', 'l', 'l', 'o']{'a': 1, 'b': 2}
Both implicit and explicit conversions play a crucial role in data handling, but it should also be noted that type conversion also comes with some common pitfalls:
- Converting a string with non-numeric characters to an integer raises an error:
int("hello") # ValueError: invalid literal for int()
- Converting a float to an integer removes the decimal part, leading to data loss.
- Converting an improperly formatted list into a dictionary can raise an error.
Now that we have explored checking and converting data types, let’s examine best practices to ensure consistency and avoid these common pitfalls.
Best practices for working with data types
Consistently handling data types ensures code reliability and prevents unexpected errors. To achieve this, several best practices should be followed:
- Validating user input before performing operations prevents type-related errors. For example, when accepting numerical input, checking whether it can be safely converted ensures smooth execution:
user_input = input("Enter a number: ")if user_input.isdigit():number = int(user_input)print("Valid number:", number)else:print("Invalid input. Please enter a numeric value.")
Here, the isdigit()
method checks whether the input string consists only of numeric digits.
- Using
isinstance()
is recommended when checking for multiple data types. Unliketype()
, it allows flexible type validation and supports inheritance:
def process_value(value):if isinstance(value, (int, float)):print("Numeric value:", value * 2)else:print("Not a number")process_value(10) # Numeric value: 20process_value("text") # Not a number
- Unnecessary type conversions should be avoided to improve performance. Converting data repeatedly increases processing overhead:
# Inefficient: Converts string to int multiple timesnum = int("100") + int("200")# Efficient: Convert once and reusenum1, num2 = int("100"), int("200")result = num1 + num2
By following these best practices, handling data types becomes more efficient and less error-prone.
Conclusion
This article explored how to check data types using type()
and isinstance()
, highlighting their differences and best use cases. It also covered implicit and explicit type conversion, ensuring smooth data handling. Following best practices, such as validating inputs and minimizing unnecessary conversions, helps improve code reliability and performance.
To build a strong foundation in Python’s data types and other core concepts, check out Codecademy’s Learn Python 3 course.
Frequently Asked Questions
1. What is the difference between type()
and isinstance()
in Python?
type()
checks the exact type of an object, while isinstance()
checks if an object belongs to a class or its subclasses, making it more flexible.
2. How to convert one data type to another in Python?
Built-in functions like int()
, float()
, str()
, and list()
help convert data types. For example, int("10")
converts a string to an integer.
3. Why is type conversion important in Python?
Type conversion ensures compatibility between different data types when performing operations, preventing errors like adding a string to an integer.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
Additional Important Java Topics
Learn about a few important topics in Java that supplement the information covered in our Learn Java course. - Article
Basic Data Types
C++ is a strongly typed language. - Article
How to Convert a String to an Integer in C++
Learn how to convert string to integer in C++ using different methods like `std::stoi`, `std::istringstream`, `std::atoi`, `std::strtol`, `std::sscanf `, and `for` loop.
Learn more on Codecademy
- Free course
Learn TypeScript
Learn TypeScript, a superset of JavaScript that adds types to make the language scale!Intermediate10 hours - Free course
Learn C#: References
Unlock the power of references, an essential aspect of object-oriented programming in C#.Beginner Friendly3 hours - Career path
Business Intelligence Data Analyst
BI Data Analysts use Python and SQL to query, analyze, and visualize data — and Tableau and Excel to communicate findings.Includes 18 CoursesWith CertificateBeginner Friendly50 hours