type() and isinstance() in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
type() function do in Python?Solution
Step 1: Understand the purpose of
Thetype()type()function returns the exact type of the given object, likeint,str, orlist.Step 2: Compare with other options
isinstance()checks type inheritance, not exact type. Conversion or creation of types is not done bytype().Final Answer:
It returns the exact type of an object. -> Option DQuick Check:
type(obj)= exact type [OK]
- Confusing type() with isinstance()
- Thinking type() converts or creates types
- Assuming type() checks subclass relationships
x is an instance of int?Solution
Step 1: Recall the syntax of isinstance()
The correct syntax isisinstance(object, class_or_tuple). So,isinstance(x, int)checks ifxis an int or subclass.Step 2: Analyze other options
type(x) == isinstance(int) mixes type() and isinstance() wrongly. isinstance(int, x) reverses arguments. type(x) is int() incorrectly calls int as a function.Final Answer:
isinstance(x, int) -> Option CQuick Check:
isinstance(x, int)correct syntax [OK]
- Swapping arguments in isinstance()
- Using type() with wrong comparison
- Calling type names as functions in checks
class Animal:
pass
class Dog(Animal):
pass
x = Dog()
print(isinstance(x, Animal))
print(type(x) == Animal)Solution
Step 1: Understand isinstance() with inheritance
xis an instance ofDog, which is a subclass ofAnimal. So,isinstance(x, Animal)returnsTrue.Step 2: Understand type() equality check
type(x)returnsDog, which is not equal toAnimal. So,type(x) == AnimalreturnsFalse.Final Answer:
True\nFalse -> Option AQuick Check:
isinstance()checks inheritance,type()exact type [OK]
- Assuming type() checks inheritance
- Confusing output order
- Thinking isinstance() returns False for subclass
def check_number(n):
if type(n, int):
return True
else:
return False
print(check_number(5))Solution
Step 1: Check type() usage
type()takes one argument to return the type. Using two arguments liketype(n, int)is invalid and causes a TypeError.Step 2: Identify correct usage
To check ifnis an int, useisinstance(n, int). The return statements and print syntax are correct.Final Answer:
type() is used with two arguments incorrectly. -> Option AQuick Check:
type()needs one argument [OK]
- Passing two arguments to type()
- Confusing type() and isinstance() syntax
- Thinking return needs parentheses
class MyInt(int):
pass
items = [123, 'hello', 45.6, True, MyInt(456)]
. You want to create a new list containing only integers (including booleans, since they are subclasses of int). Which code correctly uses isinstance() to do this?Solution
Step 1: Understand subclass behavior with isinstance()
Booleans are subclasses of int in Python, soisinstance(True, int)returnsTrue. Usingisinstance(x, int)includes both ints and bools.Step 2: Compare with other options
ints = [x for x in items if type(x) == int] excludes bools becausetype(True)isbool, notint. ints = [x for x in items if isinstance(x, bool)] selects only bools, not ints. ints = [x for x in items if type(x) is int or type(x) is bool] is verbose and misses subclass flexibility.Final Answer:
ints = [x for x in items if isinstance(x, int)] -> Option BQuick Check:
isinstance()includes subclasses [OK]
- Using type() == int excludes bools
- Selecting only bools instead of ints
- Using complex or incorrect type checks
