Built-in Functions
len, type, isinstance
Type checking, length measurement, and inheritance-aware type tests
Interview: Common in interviews — isinstance vs type() and duck typing are frequently discussed
len(), type(), and isinstance() are fundamental built-in functions for inspecting objects. len() measures size, type() returns exact type, and isinstance() checks if an object is an instance of a class or its subclasses. Understanding the difference between type() and isinstance() is a common interview topic.
len() Function
- Works on: Lists, tuples, strings, dicts, sets, ranges, bytes, and any object with
__len__ - Returns: Non-negative integer — the number of items
- Custom classes: Implement
__len__(self)to make your objects work with len() - O(1) for most: Python containers store their length — len() is instant, not O(n)
type() vs isinstance()
- type(x): Returns the exact type of x — doesn't consider inheritance
- isinstance(x, T): Returns True if x is an instance of T or any subclass of T
- Always prefer isinstance:
type(x) == intfails for bool (which IS an int subclass);isinstance(True, int)correctly returns True - Multiple types:
isinstance(x, (int, float))— checks against multiple types with a tuple
type() vs isinstance() — The Interview Answer
type(True) == int is False (type returns bool). isinstance(True, int) is True (bool is a subclass of int). Always use isinstance() for type checking — it respects inheritance and works with subclasses.
issubclass()
- Checks classes, not instances:
issubclass(bool, int)is True - Same class:
issubclass(int, int)is True (a class is a subclass of itself) - Multiple classes:
issubclass(MyClass, (Base1, Base2))
Duck Typing: The Pythonic Approach
Python prefers duck typing over explicit type checking: "If it walks like a duck and quacks like a duck, it's a duck." Instead of isinstance(x, list), try using the object and catch exceptions. Use collections.abc for abstract type checks: isinstance(x, Sequence).
Use Cases
Input validation — checking argument types before processing
Building polymorphic functions that handle different types appropriately
Custom container classes with __len__ for collection-like behavior
Abstract type checking with collections.abc for duck typing
Debugging and introspection during development
Common Mistakes
Using type() == instead of isinstance() — fails for subclasses like bool/int
Checking for specific types (list) when abstract types (Sequence) are more flexible
Forgetting that len() requires __len__ — custom classes need to implement it
Over-checking types — Python favors duck typing and EAFP over explicit type checks
Not knowing that bool is a subclass of int — True == 1, isinstance(True, int) is True