type() and isinstance() in Python - Time & Space Complexity
We want to understand how checking an object's type affects the time it takes to run a program.
Specifically, how does using type() or isinstance() grow with input size?
Analyze the time complexity of the following code snippet.
def count_strings(items):
count = 0
for item in items:
if isinstance(item, str):
count += 1
return count
This code counts how many strings are in a list of items.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the program checks more items one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks |
| 100 | About 100 type checks |
| 1000 | About 1000 type checks |
Pattern observation: The number of checks grows directly with the number of items.
Time Complexity: O(n)
This means the time to count strings grows in a straight line as the list gets longer.
[X] Wrong: "Using isinstance() or type() is slow and makes the program much slower as the list grows."
[OK] Correct: Each type check is very fast and only happens once per item, so the total time grows steadily, not wildly.
Understanding how simple checks like isinstance() scale helps you explain your code's efficiency clearly and confidently.
"What if we checked types inside a nested loop? How would the time complexity change?"