Python Type Detectives: Unveiling Data Types with type() and isinstance()
There are two main ways to find out the data type of a variable in Python:
Here's a summary:
- type(): Tells you the exact class of the variable.
- isinstance(): Checks if the variable belongs to a particular data type (including subclasses).
In general, using isinstance()
is preferred for type checking because it's more flexible and aligns better with Python's "duck typing" philosophy, which emphasizes what an object can do rather than its exact type.
# Example code showcasing how to determine data types in Python
# Assigning variables with different data types
name = "Bard" # String
age = 1 # Integer
gpa = 3.8 # Float
# Using type() function
print(f"Type of name: {type(name)}") # Output: <class 'str'>
print(f"Type of age: {type(age)}") # Output: <class 'int'>
print(f"Type of gpa: {type(gpa)}") # Output: <class 'float'>
# Using isinstance() function
print(f"\nIs name a string? {isinstance(name, str)}") # Output: True
print(f"Is age a float? {isinstance(age, float)}") # Output: False
print(f"Is gpa an integer? {isinstance(gpa, int)}") # Output: False (gpa is a float)
This code outputs the following:
Data Type | Output |
---|---|
Type of name | <class 'str'> |
Type of age | <class 'int'> |
Type of gpa | <class 'float'> |
Is name a string? | True |
Is age a float? | False |
Is gpa an integer? | False |
Here's an example of using dir()
:
# Example using dir()
my_list = [1, 2, 3]
print(dir(my_list)) # This will show list methods like append(), remove(), etc.
Important points to remember:
type()
andisinstance()
are generally the recommended methods for type checking.dir()
can provide hints but isn't a foolproof way to determine type.- Duck typing can be useful in specific situations but requires caution to avoid errors.
python types