Python Glossary Русский

Python 3.4+operatorfunction

operator.length_hint

sequences

Estimates an object's length: exact via len or approximate via __length_hint__ (for iterators); the second argument is the default.

Syntax

operator.length_hint(obj, default=0)

It is an estimate, not a promise: an iterator may yield more or fewer items. A generator reports no length at all, so length_hint returns the default — 0 unless you pass another. It mostly serves authors of collections who want to preallocate; in everyday code use len for an exact size, or list(it) for an iterator.

Examples

import operator
print(operator.length_hint([1, 2, 3]))   # → 3
it = iter([1, 2, 3])
print(operator.length_hint(it))  # → 3
print(next(it))  # → 1
print(operator.length_hint(it))  # → 2
print(operator.length_hint((x for x in range(5)), 10))  # → 10

See also

Open in the full glossarydocs.python.orgReport an inaccuracy