Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

len: element count, not memory size

len returns the number of elements in an object that supports length. For strings it counts Unicode code points, not bytes or necessarily the characters a person sees.

Version: Python 3.14

Syntax

len(object, /)

For a list, len([4, 8]) is 2. A dictionary counts keys, not keys and values together; assigning again to the same key does not add an element. An empty container has length 0. The result is a non-negative integer.

String length is not the size of encoded data. A letter followed by a separate combining mark can look like one character while containing two code points. The example compares such a string with its UTF-8 representation. Counting user-perceived characters requires grapheme segmentation rather than just len.

Not every object has a length: len(3) and the length of an ordinary generator raise TypeError. Turning a generator into a list consumes it and can require considerable memory. If you only need a count, count during iteration, remembering that this also consumes the iterator.

A custom class can define its length through __len__. Do not assume constant cost for every class. In CPython, a length exceeding sys.maxsize can raise OverflowError, even if the object represents a larger range.

Examples

text = "e\u0301"
print(len(text), len(text.encode("utf-8")))
print(len({"a": 1, "a": 2}))
values = (number for number in range(3))
try:
    print(len(values))
except TypeError:
    print("TypeError")

Result

2 3
1
TypeError

Sources