0
0
Pythonprogramming~5 mins

type() and isinstance() in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: type() and isinstance()
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets bigger, the program checks more items one by one.

Input Size (n)Approx. Operations
10About 10 type checks
100About 100 type checks
1000About 1000 type checks

Pattern observation: The number of checks grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to count strings grows in a straight line as the list gets longer.

Common Mistake

[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.

Interview Connect

Understanding how simple checks like isinstance() scale helps you explain your code's efficiency clearly and confidently.

Self-Check

"What if we checked types inside a nested loop? How would the time complexity change?"