Python Glossary Русский

all Python 3Built-in functionsfunction

len()

Built-in functions

Returns the number of items in an object (its length): a sequence, set, dict or string.

Syntax

len(obj)

len() does not count anything: containers keep their size, so the call is O(1) even for a million items. It does require __len__, though — a generator or any other iterator has no length and raises TypeError, so count a stream with sum(1 for _ in it) or materialise it into a list first.

Examples

print(len([1, 2, 3]))     # → 3
print(len('abcd'))        # → 4
print(len({'a': 1}))      # → 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy