Type checking using type() in Python - Time & Space Complexity
We want to understand how long it takes to check the type of a value using the type() function in Python.
The question is: How does the time to check a type change when we use type() on different inputs?
Analyze the time complexity of the following code snippet.
values = [123, 'hello', 3.14, [1, 2, 3], {'a': 1}]
for val in values:
if type(val) == int:
print(f"{val} is an integer")
This code checks the type of each item in a list and prints a message if the item is an integer.
- Primary operation: Looping through each item in the list and calling
type()on it. - How many times: Once for each item in the list (n times, where n is the list size).
Each item requires one type check, so the total work grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The time grows in a straight line as the list gets bigger.
Time Complexity: O(n)
This means the time to check types grows directly with the number of items you check.
[X] Wrong: "Checking the type with type() takes the same time no matter how many items there are, so it is constant time overall."
[OK] Correct: While each type() call is fast, you do it once per item, so total time adds up as the list grows.
Understanding how simple operations like type checking scale helps you explain code efficiency clearly and confidently in interviews.
"What if we used isinstance() instead of type()? How would the time complexity change?"