Special Method Protocols
__len__() — containers protocol
Implement len() with a nonnegative integer. If __bool__ is absent, zero length means false. CPython requires the length to fit Py_ssize_t for len().
Formal Syntax & Structure
python syntaxpython
def __len__(self):Return Value
int
Number of elements.
Working Example
Example Snippetpython
class Bag: def __init__(self, items): self.items=items def __len__(self): return len(self.items)print(len(Bag([1,2,3])))