inspection
len()
Returns the number of items in a container. Calls the object's __len__ method.
len(s) Parameters
| Parameter | Purpose |
|---|---|
| s | Sequence, mapping, set, or any object implementing __len__ |
| returns | Non-negative int; raises TypeError if __len__ is missing |
Examples
len('hello') Returns 5
len([1, 2, 3]) Returns 3
len({'a': 1, 'b': 2}) Returns 2 (number of keys)
Gotcha
Does not work on generators or iterators (no __len__) — you must materialize them or use sum(1 for _ in it).
Related built-ins
type()
Returns the type of an object, or dynamically creates a new type when called with three arguments. type(x) is the runtime class of x.
isinstance()
Returns True if the object is an instance of classinfo (a class or tuple of classes). Respects the class hierarchy — subclasses count.
hasattr()
Returns True if the object has an attribute with the given name. Implemented by calling getattr() and catching AttributeError.
getattr()
Returns the value of the named attribute of object. If the attribute is missing, returns default (if given) or raises AttributeError.