ZetCode

Python __len__ Method

Last modified November 18, 2026 Python 3.15

Calling len(obj) invokes type(obj).__len__(obj). The method reports the size of a container and must return a non-negative integer. This article covers the basic delegation, truth testing, the errors raised for invalid return values, logical sizes that differ from physical storage, recursive counting, and cached length calculation without any file I/O.

Basic length reporting

The usual implementation delegates to a stored collection. Python's len() built-in calls the hook directly rather than going through a generic attribute lookup.

basic_len.py
class ShoppingCart:
    def __init__(self):
        self.items = []

    def add_item(self, item):
        self.items.append(item)

    def __len__(self):
        return len(self.items)

    def __repr__(self):
        return f"ShoppingCart({self.items})"


cart = ShoppingCart()
cart.add_item("Apple")
cart.add_item("Banana")
print(len(cart))
print(cart)

The cart reports two items because __len__ returns the length of its internal list. The hook is called once by len(); the second line simply prints the object's representation.

$ python basic_len.py
2
ShoppingCart(['Apple', 'Banana'])

Length and truth testing

When a class has __len__ but no __bool__, Python uses the length for truth testing: a zero length is falsy and any positive length is truthy.

bool_len.py
class Basket:
    def __init__(self, *items):
        self.items = list(items)

    def __len__(self):
        return len(self.items)

    def __repr__(self):
        return f"Basket({len(self.items)} items)"


empty = Basket()
full = Basket("apple", "pear")
print(len(empty), bool(empty))
print(len(full), bool(full))
if empty:
    print("not reached")
else:
    print("empty is falsy")

The empty basket is falsy because its length is zero. Defining __bool__ would override this rule if you needed a different notion of truth for the class.

$ python bool_len.py
0 False
2 True
empty is falsy

Invalid return values

Python validates the result of __len__. A float raises TypeError, a negative integer raises ValueError, and a class without the hook has no length at all. A bool works because it is a subclass of int.

len_errors.py
class NoLength:
    pass


class FloatLength:
    def __len__(self):
        return 3.5


class NegativeLength:
    def __len__(self):
        return -1


for obj in (NoLength(), FloatLength(), NegativeLength()):
    try:
        print(len(obj))
    except (TypeError, ValueError) as e:
        print(type(e).__name__, e)

Each invalid object fails with a distinct message. The value must be an integer in the range from zero up to sys.maxsize; larger values raise OverflowError.

$ python len_errors.py
TypeError object of type 'NoLength' has no len()
TypeError 'float' object cannot be interpreted as an integer
ValueError __len__() should return >= 0

Logical size of a fixed container

A container may report a capacity instead of the number of elements it currently holds. The hook should describe the abstraction the class offers, not necessarily the raw storage.

fixed_queue.py
class FixedQueue:
    def __init__(self, size):
        self.size = size
        self._items = [None] * size
        self._pointer = 0

    def enqueue(self, item):
        self._items[self._pointer] = item
        self._pointer = (self._pointer + 1) % self.size

    def __len__(self):
        return self.size

    def __repr__(self):
        return f"FixedQueue(capacity={self.size})"


queue = FixedQueue(5)
queue.enqueue("A")
queue.enqueue("B")
print(len(queue))
print(queue)

The queue always reports 5, its capacity, even after only two enqueues. That is a deliberate design choice: the class models a fixed-size buffer. Document such choices so callers are not surprised by the result.

$ python fixed_queue.py
5
FixedQueue(capacity=5)

Counting set bits

For a bitmask, the useful size is the number of active bits. The hook can compute it from the mask on demand.

bitmask_len.py
class Bitmask:
    def __init__(self, size):
        self.size = size
        self.mask = 0

    def set_bit(self, position):
        self.mask |= 1 << position

    def __len__(self):
        return bin(self.mask).count("1")

    def __repr__(self):
        return f"Bitmask({self.mask:08b})"


mask = Bitmask(8)
mask.set_bit(2)
mask.set_bit(5)
print(mask)
print(len(mask))

Bits 2 and 5 are set, so the mask prints as 00100100 and has length 2. The size attribute records the field width, while __len__ reports how many bits are active.

$ python bitmask_len.py
Bitmask(00100100)
2

Recursive length of a tree

A tree node can define its length as the number of nodes in its subtree. Each node contributes one, plus the lengths of all its children.

tree_len.py
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []

    def add_child(self, node):
        self.children.append(node)

    def __len__(self):
        return 1 + sum(len(child) for child in self.children)

    def __repr__(self):
        return f"TreeNode({self.value})"


root = TreeNode("Root")
child1 = TreeNode("Child1")
child2 = TreeNode("Child2")
child1.add_child(TreeNode("Grandchild"))
root.add_child(child1)
root.add_child(child2)
print(len(root), len(child1), len(child2))

The whole tree has four nodes, the first child has two (itself and the grandchild), and the second child has only itself. For very deep trees an iterative traversal would avoid recursion-depth limits.

$ python tree_len.py
4 2 1

Caching an expensive length

When computing the length is expensive, cache it after the first call. The example uses an in-memory iterable so it stays self-contained, and shows how operator.length_hint also consults __len__.

cached_len.py
import operator


class Dataset:
    def __init__(self, values):
        self.values = list(values)
        self._length = None

    def __iter__(self):
        return iter(self.values)

    def __len__(self):
        if self._length is None:
            print("computing")
            self._length = sum(1 for _ in self.values)
        return self._length


data = Dataset("abcdef")
print(len(data))
print(len(data))
print(operator.length_hint(data))
print(data._length)

Only the first len() call prints computing; the later calls reuse the cached value. operator.length_hint() also uses __len__ when it is available, so it reports 6 without a new calculation.

$ python cached_len.py
computing
6
6
6
6

Best practices

A few rules keep __len__ predictable:

Source

object.__len__ - Python documentation

len() - Python documentation

Truth value testing - Python documentation

operator.length_hint - Python documentation

In this article we have implemented the __len__ method. We have covered basic reporting, truth testing, invalid return values, logical sizes, bitmasks, recursive trees and cached lengths. For related topics, see Python __bool__ method, Python __iter__ method, and Python len() function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.