0
0
Pythonprogramming~5 mins

Type checking using type() in Python - Time & Space Complexity

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

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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).
How Execution Grows With Input

Each item requires one type check, so the total work grows directly with the number of items.

Input Size (n)Approx. Operations
1010 type checks
100100 type checks
10001000 type checks

Pattern observation: The time grows in a straight line as the list gets bigger.

Final Time Complexity

Time Complexity: O(n)

This means the time to check types grows directly with the number of items you check.

Common Mistake

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

Interview Connect

Understanding how simple operations like type checking scale helps you explain code efficiency clearly and confidently in interviews.

Self-Check

"What if we used isinstance() instead of type()? How would the time complexity change?"