Python Glossary Русский

all Python 3operatorfunction

operator.index

arithmetic

Returns a converted to an integer via the __index__() protocol — equivalent to a.__index__(); since 3.10 the result always has exact type int.

Syntax

operator.index(a)

It is stricter than int(): a float is refused outright — index(3.0) raises TypeError rather than truncating. It accepts bool, a subclass of int: index(True) gives 1. Use it when a value will become an index or slice bound: that is how range and list.__getitem__ behave, and a NumPy integer with __index__ passes without an explicit conversion.

Examples

# Python 3.10+
import operator
print(operator.index(5))                   # → 5
print(operator.index(True))                # → 1
print(type(operator.index(True)))          # → <class 'int'>
print(operator.__index__(-3))              # → -3
print([10, 20, 30][operator.index(True)])  # → 20

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy