Homeโบ
Tutorialsโบ
Python 3โบ
Lesson 11: Python Type Checking with type(), isinstance() & Type Casting
Python Type Checking with type(), isinstance() & Type Casting
๐ Python 3
๐ข Lesson 11 of 12
๐ Phase 1: Python Basics
๐
2026 Edition
Learn how to inspect data types with type() and isinstance(), understand implicit type coercion, and perform explicit type casting (int, float, str, list).
1Inspecting Types: type() vs isinstance()
Python provides two main built-in functions for runtime type inspection:
type(obj): Returns the exact class/type of the object.
isinstance(obj, class_or_tuple): Checks if an object is an instance of a class or any of its subclasses (recommended for robust OOP checks).
2Implicit Type Conversion (Type Coercion)
Python automatically converts smaller numeric types to wider types to prevent data loss. For example, adding an int and a float automatically yields a float:
num_int = 10 # int
num_float = 2.5 # float
res = num_int + num_float # res becomes 12.5 (float)
3Explicit Type Casting Functions
int("123") -> Converts string/float to integer (e.g. int(7.8) -> 7 truncates decimal).
float("3.14") -> Converts string/integer to float.
str(100) -> Converts any object to its string representation.
list("abc") -> ['a', 'b', 'c'].
tuple([1, 2]) -> (1, 2).
set([1, 2, 2, 3]) -> {1, 2, 3} (removes duplicates).
๐ป Complete Executable Code Example
# Type inspection
data = 42.5
print(f"type(data): {type(data)}")
print(f"isinstance(data, float): {isinstance(data, float)}")
print(f"isinstance(data, (int, float)): {isinstance(data, (int, float))}")
# Explicit type conversions
str_score = "95"
int_score = int(str_score)
print(f"
Parsed Score + Bonus: {int_score + 5}")
# Converting between collections
colors_list = ["red", "blue", "green", "red", "blue"]
unique_colors = set(colors_list)
print("Original List:", colors_list)
print("Unique Set:", unique_colors)
# Safe integer casting with error handling
def safe_int_convert(val, default=0):
try:
return int(val)
except (ValueError, TypeError):
return default
print("safe_int_convert('500'):", safe_int_convert("500"))
print("safe_int_convert('invalid_text'):", safe_int_convert("invalid_text"))
โ ๏ธ Common Pitfall: Trying to cast float strings directly with int("3.14")
Calling int("3.14") raises ValueError. To parse a float string to an integer, either convert to float first: int(float("3.14")) or clean the string before casting.
๐ป Try It Yourself โ Hands-on Practice Challenge
Convert a CSV-formatted string of numbers into a sorted list of integers.
csv_data = "45, 12, 88, 3, 99, 24"
# Split, strip whitespace, and cast to int
numbers = [int(num.strip()) for num in csv_data.split(",")]
numbers.sort()
print("Sorted Integers:", numbers)
print("Sum:", sum(numbers), "Average:", sum(numbers)/len(numbers))
Run This Code in Our Online Compiler โ
โ Frequently Asked Questions (FAQ)
Q: Why is isinstance() preferred over type() == ... ?
isinstance() correctly accounts for inheritance hierarchies (e.g. isinstance(True, int) is True because bool inherits from int), making functions open for polymorphism.
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026