We use type() and isinstance() to check what kind of thing (type) a value or object is. This helps us understand or control how our program works.
type() and isinstance() in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
type(object) isinstance(object, classinfo)
type(object) returns the exact type of the object.
isinstance(object, classinfo) checks if the object is an instance of the classinfo or its subclasses.
Examples
Python
type(5) type('hello') type([1, 2, 3])
Python
isinstance(5, int) isinstance('hello', str) isinstance([1, 2, 3], list)
bool is a subclass of int.Python
isinstance(True, int)
isinstance is more flexible with subclasses.Python
type(5) == int isinstance(5, int)
Sample Program
This program prints the type of the value using type() and then uses isinstance() to print a friendly message about what kind of data it is.
Python
def check_type(value): print(f'Value: {value}') print(f'type(): {type(value)}') if isinstance(value, int): print('This is an integer.') elif isinstance(value, str): print('This is a string.') elif isinstance(value, list): print('This is a list.') else: print('Unknown type.') check_type(10) check_type('hello') check_type([1, 2, 3]) check_type(3.14)
Important Notes
type() gives the exact type, so it does not consider inheritance.
isinstance() is better when you want to allow subclasses or multiple types.
Use isinstance() for safer and more flexible type checking in most cases.
Summary
type() tells you the exact type of an object.
isinstance() checks if an object belongs to a type or its children types.
Use these to make your program understand and handle data correctly.
Practice
1. What does the
type() function do in Python?easy
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]
Hint: Remember: type() gives exact type, isinstance() checks inheritance [OK]
Common Mistakes:
- Confusing type() with isinstance()
- Thinking type() converts or creates types
- Assuming type() checks subclass relationships
2. Which of the following is the correct syntax to check if variable
x is an instance of int?easy
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]
Hint: Use isinstance(obj, Type) to check type safely [OK]
Common Mistakes:
- Swapping arguments in isinstance()
- Using type() with wrong comparison
- Calling type names as functions in checks
3. What will be the output of this code?
class Animal:
pass
class Dog(Animal):
pass
x = Dog()
print(isinstance(x, Animal))
print(type(x) == Animal)medium
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]
Hint: isinstance() True if subclass; type() True only if exact type [OK]
Common Mistakes:
- Assuming type() checks inheritance
- Confusing output order
- Thinking isinstance() returns False for subclass
4. Find the error in this code snippet:
def check_number(n):
if type(n, int):
return True
else:
return False
print(check_number(5))medium
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]
Hint: type() takes one argument; use isinstance() to check type [OK]
Common Mistakes:
- Passing two arguments to type()
- Confusing type() and isinstance() syntax
- Thinking return needs parentheses
5. You have a list of mixed data:
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?hard
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]
Hint: Use isinstance(x, int) to include bools as ints [OK]
Common Mistakes:
- Using type() == int excludes bools
- Selecting only bools instead of ints
- Using complex or incorrect type checks
