Kodeclik Blog
How to find the type of a Python variable
To find the type of a Python variable, we use the built-in type() function. You can use this function to test your own understanding of Python and also to use it in practical programs to make them more robust to a range of inputs.
Basics
Let us learn how type() works by considering a most basic Python variable, i.e., integers. Note that an integer is a whole number without a decimal point, so if we use the type() operator with an integer variable we will get this output:
x = 10
print(type(x)) # Output: <class 'int'>
The output basically says that the variable x is of class (or type) “int” (denoting integer).
A float represents a real number with decimal points.
pi = 3.14
print(type(pi)) # Output: <class 'float'>
A string is a sequence of characters enclosed in quotes. So for such an input:
name = "Alice"
print(type(name)) # Output: <class 'str'>
We will get “<class 'str'>” as output.
Booleans are either True or False. Accordingly:
is_active = True
print(type(is_active)) # Output: <class 'bool'>
This idea can be extended to more complex data structures such as lists:
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # Output: <class 'list'>
Note that the output just says it is of class list, not a list of strings. This is because in Python lists can contain mixed types.
A dictionary holds key-value pairs:
person = {"name": "Bob", "age": 25}
print(type(person)) # Output: <class 'dict'>
A set is an unordered collection of unique items:
unique_ids = {101, 102, 103}
print(type(unique_ids)) # Output: <class 'set'>
Each call to type() inspects the variable and tells you what kind of data it holds. This is useful for debugging and understanding how Python interprets your variables.
Next are five practical scenarios where you'd want to check a variable's type, with code examples and demonstrations.
Example 1: Input Validation for Functions
Suppose you are writing a function that requires an integer argument. You can use type() to do input validation, i.e., ensure that the function is being used as intended.
def square(x):
if type(x) != int:
raise TypeError("Input must be an integer")
return x * x
print(square(5)) # Output: 25
print(square("five")) # Raises TypeError
Example 2: Processing Mixed Data Types in Lists
Suppose you have a list containing integers and strings. Lets say you want to do something different depending on the type, e.g., you might want to double integers but capitalize strings. Here is some Python code to do so:
my_list = [2, "hello", 3, "world"]
processed = []
for item in my_list:
if type(item) == int:
processed.append(item * 2)
elif type(item) == str:
processed.append(item.upper())
print(processed) # Output: [4, 'HELLO', 6, 'WORLD']
Example 3: Deserializing JSON Data
Sometimes JSON data fields might inadvertently mix types. Checking using type() and then modifying accordingly helps prevent bugs. Consider the below code:
import json
data = '{"count": "10"}'
parsed = json.loads(data)
count = parsed["count"]
if type(count) == int:
actual_count = count
elif type(count) == str:
actual_count = int(count)
print(actual_count) # Output: 10
Here if the count field is of type string (not intended) we use the int() typecasting function to convert it from string to integer.
Example 4: Handling Pandas Dataframe Column Types
When manipulating Dataframes, you may need to ensure a column is of a specific type:
import pandas as pd
df = pd.DataFrame({"vals": [1, 2, 3]})
print(type(df["vals"])) # Output: <class 'pandas.core.series.Series'>
print(type(df["vals"][0])) # Output: <class 'int'>
Example 5: Debugging
In general, you can use this function during debugging to identify complex issues. By printing variable types we will know what is going on with our program:
def process(value):
print("Type of value:", type(value))
# Based on type, take action
if type(value) == list:
return [v*2 for v in value]
elif type(value) == int:
return value*2
print(process([1,2,3])) # Output: Type of value: <class 'list'>, [2,4,6]
print(process(10)) # Output: Type of value: <class 'int'>, 20
Summary
To summarize, type() is crucial for type validation, debugging, mixed-data processing, and writing robust code in Python.
Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.